Reputation: 560
I completely understand this form:
Set<T> set = new HashSet<>();
list.stream().allMatch(t -> set.add(t));
// And that
list.stream().allMatch(set::add);
But this ad-hoc instance really confuses me:
list.stream().allMatch(new HashSet<>()::add);
The most interesting is that hashset instantiated only one time.
Founded in this topic
Upvotes: 0
Views: 178
Reputation: 7098
It's the same as the first expression except that you don't keep a reference to the newly created set in your context. If you're not going to need the set's value after the allMatch
invocation, it's the same. It's essentially a method reference expression with the newly created instance of HashSet
. While it might be confusing at first sight, a HashSet
is only created once, then the method reference bound to this newly created instance and used as such in the evaluation of the allMatch
operation.
While it might be a working solution, it can be dangerous, especially with non-sequential (parallel) stream pipelines because it violates the allMatch
predicate's statelessness requirement in the API contract.
Upvotes: 4