Here is different ways to find Java Find duplicate objects in list like Java Find duplicate objects in list using Set and Java Find duplicate objects in list using Stream Group by:

Java Find duplicate objects in list using Set

java.util.List<String> duplicates = Arrays.asList("A", "B", "B", "C", "D", "D", "Z", "E", "E");
     java.util.HashSet unique=new HashSet();
     System.out.println("Java Find duplicate objects in list using Set");  
     for (String s:duplicates){
         if(!unique.add(s)){   //  // java.util.Set only unique object so if object will not bee add in Set it will return false so can consider it as Duplicate
             System.out.println(s);
         }
     }

Output:

Java Find duplicate objects in list using Set
B
D
E

 

Java Find duplicate objects in list using Stream Group by

In Java Stream perform group by operation based on that we can find duplicate object from collection or list.

java.util.List<String> list = Arrays.asList("A", "B", "B", "C", "D", "D", "Z", "E", "E");
      list.stream().collect(Collectors.groupingBy(Function.identity(),     
              Collectors.counting()))                                             // perform group by count
          .entrySet().stream()
          .filter(e -> e.getValue() > 1L)                                        // using take only those element whose count is greater than 1
          .map(e -> e.getKey())                                                  // using map take only value   
          .collect(Collectors.toList())                                        // convert group by result to list      
          .forEach(System.out::println);

Output:

B
D
E

References:

Java java.util.Set document

Java Stream Group by document

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *