Search code examples
javafunctional-interface

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

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.