Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8, Streams to find the duplicate elements

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 ?

like image 363
Siva Avatar asked Dec 28 '14 14:12

Siva


People also ask

How do I find duplicates in java 8?

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.

How do I filter duplicates in stream?

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.

How do you find duplicates in a list in java?

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.


1 Answers

You can use Collections.frequency:

numbers.stream().filter(i -> Collections.frequency(numbers, i) >1)                 .collect(Collectors.toSet()).forEach(System.out::println); 
like image 112
Bao Dinh Avatar answered Sep 23 '22 06:09

Bao Dinh