user and
user and

Reputation: 560

Understanding method reference with newly created instance

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

Answers (1)

N&#225;ndor Előd Fekete
N&#225;ndor Előd Fekete

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

Related Questions