Reputation: 1313
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
Upvotes: 6
Views: 455
Reputation: 394016
new HashSet<>()::add
is a method reference referencing a specific instance of a HashSet
.
It's equivalent to creating an instance of a HashSet
outside that method, storing a reference to it in a variable set
, and using the method reference set::add
instead. i.e. it will always operate on the same HashSet
instance.
The lambda expression behaves differently, since the body of the lambda expression is executed each time allMatch()
has to apply the Predicate
to an element of the Stream
. And each time the body is executed, a new HashSet
instance is created.
Upvotes: 7