Search code examples
javalambdacollectorstolist

Why I use "Collectors.toList()" rather than "Collectors::toList" in Java 8 Lambda?


Usually after a flatMap, we use collect(Collectors.toList()) to collect data and return a List.

But why can't I use Collectors::toList instead? I tried to use it, but got a compilation error.

I tried to search this, but cannot find any explanation.

Many thanks.


Solution

  • You are calling the <R, A> R collect(Collector<? super T, A, R> collector) method of the Stream interface. Collectors.toList() returns a Collector<T, ?, List<T>>, which matches the required type of the collect method's argument. Therefore someStream.collect(Collectors.toList()) is correct.

    On the other hand, the method reference Collectors::toList cannot fit as a parameter for the collect method, since a method reference can only be passed where a functional interface is required, and Collector is not a functional interface.

    You could have passed Collectors::toList to a method that requires a Supplier<Collector>. Similarly, you can assign it to such a variable:

    Supplier<Collector<Object,?,List<Object>>> supplierOfListCollector = Collectors::toList;