java 8 get duplicates in list

Solutions on MaxInterview for java 8 get duplicates in list by the best coders in the world

showing results for - "java 8 get duplicates in list"
Jordon
13 Oct 2020
1List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
2Set<Integer> nbrRemovedSet = new HashSet<>();
3
4// Set.add() returns false if the element was already in the set.
5Set<Integer> nbrSet = numbers
6	.stream()
7  	.filter(n -> !nbrRemovedSet.add(n))
8  	.collect(Collectors.toSet());
9
10// also, we can use Collections.frequency:
11Set<Integer> nbrSet = numbers
12	.stream()
13  	.filter(i -> Collections.frequency(numbers, i) >1)
14    collect(Collectors.toSet());