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
You can use Collectors.frecuency() and Collectors.groupingBy.
This is how i do this, hope this can help you.
Map<Object,Long> finalValues = new HashMap<Object, Long>();
finalValues = Arrays.asList(new Integer[] {3, 3, 3, 1, 5, 8, 11, 4, 5 })
.stream()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
//Check the output
finalValues.entrySet().forEach(entry -> {
System.out.println("number: " + entry.getKey() + "| Times: "+ entry.getValue());
});
The output is:
number: 1| Times: 1
number: 3| Times: 3
number: 4| Times: 1
number: 5| Times: 2
number: 8| Times: 1
number: 11| Times: 1
You can even use frecuency to delete all the numbers that doesn't repeat:
Map finalValues = new HashMap();
List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});
finalValues = numbers
.stream()
.filter(x-> Collections.frequency(numbers, x) > 1)
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
//Check the output
finalValues.entrySet().forEach(entry -> {
System.out.println("number: " + entry.getKey() + "| Times: "+ entry.getValue());
});
The output is :
number: 1| Times: 2
number: 4| Times: 2
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class DuplicatedValuesInArray
{
public static void main(String args[]) {
int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };
Map<Integer, Integer> map= new HashMap<Integer, Integer>();
for(int i=0;i<array.length;i++) {
if(map.containsKey(array[i]))
map.put(array[i],map.get(array[i]) + 1);
else
map.put(array[i], 1);
}
for (Integer i : map.keySet()) {
System.out.println(i + " is contained " + map.get(i) + " times.");
}
}
}
Sort the array, then either scan it or Arrays.binarySearch
+ scan in either direction. Due to much fewer allocations and no wrapping, this can be faster, especially on larger arrays.