Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can HashSet::add be accepted as an ObjectIntConsumer?

It seems that following line is a valid implementation for collecting a stream of integers in Java:

IntStream.range(1, 100)
    .collect(HashSet::new, HashSet::add, HashSet::addAll);

But when I take into account the collect method signature in IntStream class that is

collect(Supplier<R> supplier,
 ObjIntConsumer<R> accumulator,
 BiConsumer<R, R> combiner)

, I can not understand how can HashSet::add be passed to collect method where an ObjIntConsumer is expected, since ObjIntConsumer is expecting two arguments

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void accept(T t, int value);

, but HashSet::add accepts only one argument!

>Solution :

The equivalent lambda expression for HashSet::add in your code is:

(HashSet<Integer> t, int value) -> t.add(value)

In other words, the ObjIntConsumer is accepting both the container (in this case a HashSet) and the value to be added to that container.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading