how to find out how many duplicates in list java code example
Example 1: java 8 get duplicates in list
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> nbrRemovedSet = new HashSet<>();
Set<Integer> nbrSet = numbers
.stream()
.filter(n -> !nbrRemovedSet.add(n))
.collect(Collectors.toSet());
Set<Integer> nbrSet = numbers
.stream()
.filter(i -> Collections.frequency(numbers, i) >1)
collect(Collectors.toSet());
Example 2: java find duplicate element in list
public static Set<String> findDuplicates(List<String> listContainingDuplicates) {
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
for (String yourInt : listContainingDuplicates) {
if (!set1.add(yourInt)) {
setToReturn.add(yourInt);
}
}
return setToReturn;
}