Java 8, Streams to find the duplicate elements

Example 1: Using Collections.frequency()

It compares each item with a list – Collections.frequency(list, i).
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {

List<String> obj = Arrays.asList("ant", "1", "cat", "ant",
                            "we", "java", "cat");
obj.stream().filter(i -> Collections.frequency(obj, i) > 1).
                                      collect(Collectors.toSet())
.forEach(System.out::println);

}
}
Output:
ant
cat

Example 2: Using Collectors.groupingBy()

Create a Map by Collectors.groupingBy and find elements that count > 1
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {
List<String> obj = Arrays.asList("ant", "1", "cat", "ant",
                                               "we", "java", "cat");
Set<String> result = obj.stream().
collect(Collectors.groupingBy(Function.identity(),
                                                           Collectors.counting())).
entrySet().stream().filter(m -> m.getValue() > 1).
map(Map.Entry::getKey).collect(Collectors.toSet());
result.stream().forEach(System.out::println);

}
}
Output:
ant
cat


Example 3: Using Set.add()

If the element is present in the Set already, then this Set.add() returns false.
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {

List<String> obj = Arrays.asList("ant", "1", "cat", "ant",
                                             "we", "java", "cat");
Set<String> items = new HashSet<>();
Set<String> result = obj.stream().filter(n -> !items.add((String) n)).
                             collect(Collectors.toSet());
result.stream().forEach(System.out::println);
}
}
Output:
ant
cat


More...

Comments