I want to know if my List<T>
has duplicates elements.
I have seen the method below :
public static <T> boolean areAllUnique(List<T> list){
return list.stream().allMatch(new HashSet<>()::add);
}
It works and I'm surprised why ? Because it seems a new HashSet<> is created everytime (so basically the method should always return true even if duplicates)
If I write differently the method above, it no longer works :
public static <T> boolean areAllUnique(List<T> list){
return list.stream().allMatch(t -> {
return new HashSet<>().add(t);
});
}
I'm surprised the 1st method works while the other does not. Because for me they look the same