I have an array as follows:
int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
What I wanted to do was to find the duplicate values, and print them.
So my way of doing this was to convert to ArrayList
, then to Set
and use a stream
on the Set
.
ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
Set<Integer> dup = new HashSet<>(list);
I then used a stream
to loop through it and print the values using Collections.frequency
.
dup.stream().forEach((key) -> {
System.out.println(key + ": " + Collections.frequency(list, key));
});
Which will of course print them all, even if the count is one.
I thought adding in if(key > 1)
but it's the value I want not the key.
How can I get the value in this instance to print only where value > 2
.
I could probably put in:
int check = Collections.frequency(list, key);
if (check > 1) {
but this then duplicates Collections.frequency(list, key)
in the stream
and is quite ugly.
Collection frequency means the number of times collection is provided in a given period of time.
Probably you can to use filter
to get only the values great than 2 :
dup.stream()
.filter(t -> Collections.frequency(list, t) > 2)
.forEach(key -> System.out.println(key + ": " + Collections.frequency(list, key)));
result in your case is :
11: 4
Edit
Another solution :
No need to use a Set
or Collections.frequency
you can just use :
Integer[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
Arrays.stream(array).collect(Collectors.groupingBy(p -> p, Collectors.counting()))
.entrySet().stream().filter(t -> t.getValue() > 1)
.forEach(key -> System.out.println(key.getKey() + ": " + key.getValue()));
Output
48: 2
17: 2
11: 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With