I want to detect duplicate values in a Java array. For example:
int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };
How could I get the specific
Java 8, the solution:
1. Create Map when the Key is the Value of Array and Value is counter.
2. Check if Map contains the Key increase counter or add a new set.
private static void calculateDublicateValues(int[] array) {
//key is value of array, value is counter
Map map = new HashMap();
for (Integer element : array) {
if (map.containsKey(element)) {
map.put(element, map.get(element) + 1); // increase counter if contains
} else
map.put(element, 1);
}
map.forEach((k, v) -> {
if (v > 1)
System.out.println("The element " + k + " duplicated " + v + " times");
});
}