I needed to do a similar operation for a Stream
, but couldn't find a good example. Here's what I came up with.
public static <T> boolean areUnique(final Stream<T> stream) {
final Set<T> seen = new HashSet<>();
return stream.allMatch(seen::add);
}
This has the advantage of short-circuiting when duplicates are found early rather than having to process the whole stream and isn't much more complicated than just putting everything in a Set
and checking the size. So this case would roughly be:
List<T> list = ...
boolean allDistinct = areUnique(list.stream());