EN
Java 8 - find duplicate elements in List
0 points
In this article, we would like to show you how to find duplicate elements in List working with Streams in Java 8.
In this example, we filter letters
stream and use Collections.frequency()
to find duplicate elements.
xxxxxxxxxx
1
import java.util.*;
2
import java.util.stream.Collectors;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
// create list of strings
8
List<String> letters = Arrays.asList("A", "B", "C", "B", "A");
9
10
// find duplicate elements
11
letters.stream().filter(i -> Collections.frequency(letters, i) > 1)
12
.collect(Collectors.toSet()).forEach(System.out::println);
13
}
14
}
Output:
xxxxxxxxxx
1
A
2
B