Java array repeating

Java array repeating

To find repeating elements in an array in Java, you can use a loop to iterate over the array and keep track of the elements that have already been seen.

Here is an example of how to find repeating elements in an array:

import java.util.HashSet;
import java.util.Set;

public class ArrayFindRepeatingElementsExample {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3};

        Set<Integer> seen = new HashSet<>();
        Set<Integer> repeating = new HashSet<>();

        for (int number : numbers) {
            if (!seen.add(number)) {
                repeating.add(number);
            }
        }

        System.out.println("Repeating elements: " + repeating);
    }
}
Source‮.www:‬lautturi.com

In this example, the seen set is used to store the elements that have already been seen, and the repeating set is used to store the repeating elements. The add() method of the Set interface returns false if the element is already present in the set, so we can use it to check if an element is repeating.

Alternatively, you can use a Map to keep track of the number of occurrences of each element in the array:

import java.util.HashMap;
import java.util.Map;

public class ArrayFindRepeatingElementsExample {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3};

        Map<Integer, Integer> counts = new HashMap<>();

        for (int number : numbers) {
            int count = counts.getOrDefault(number, 0);
            counts.put(number, count + 1);
        }

        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println("Repeating element: " + entry.getKey());
            }
        }
    }
}

In this example, the counts map is used to store the number of occurrences of each element in the array. The getOrDefault() method is used to get the current count for an element, or a default value of 0 if the element is not present in the map. The put() method is then used to update the count for the element. Finally, we iterate over the entries in the map and print the repeating elements (those with a count greater than 1).

Created Time:2017-11-03 00:14:40  Author:lautturi