In Java 8 Stream, filter with Set.Add() is the fastest algorithm to find duplicate elements, because it loops only one time.
Set<T> items = new HashSet<>();
return list.stream()
.filter(n -> !items.add(n))
.collect(Collectors.toSet());
The Collections.frequency is the slowest because it compares each item with a list – Collections.frequency(list, i). If we increase the size of the list, the performance will get slower.
return list.stream().filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet());
Pingback: JAVA : example of Arrays.sort() » JavaTuto