Java 8, Streams to find the duplicate elements

Siva picture Siva · Dec 28, 2014 · Viewed 151.5k times · Source

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 ?

Answer

Bao Dinh picture Bao Dinh · Sep 11, 2015

You can use Collections.frequency:

numbers.stream().filter(i -> Collections.frequency(numbers, i) >1)
                .collect(Collectors.toSet()).forEach(System.out::println);