I am trying to list out duplicate elements in the integer list say for eg,
List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});
using Streams of jdk 8. Has anybody tried out. To remove the duplicates we can use the distinct() api. But what about finding the duplicated elements ? Anybody can help me out ?
Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.
You can use the Stream. distinct() method to remove duplicates from a Stream in Java 8 and beyond. The distinct() method behaves like a distinct clause of SQL, which eliminates duplicate rows from the result set.
frequency() method. The simplest way is probably to count the frequency of each list element to determine if it is a duplicate or not. You can use the Collections. frequency() method for this, which returns the number of elements in the collection.
You can use Collections.frequency
:
numbers.stream().filter(i -> Collections.frequency(numbers, i) >1) .collect(Collectors.toSet()).forEach(System.out::println);
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