Search code examples
javajava-8java-streamcollectorsmethod-reference

why cant I refer Function.identity as method reference in collector


Can someone suggest, why am I not able to apply method reference here?

Working Code.

System.out.println(
                Arrays.stream(str.split(" "))
                        .collect(Collectors.groupingBy(Function.identity(),Collectors.counting())));  

Compilation Error, Can not resolve method

System.out.println(
            Arrays.stream(str.split(" "))
                    .collect(Collectors.groupingBy(Function::identity,Collectors::counting)));

Solution

  • Because groupingBy() expects a Function, i.e. something which takes a single argument, and returns something.

    Function.identity() returns a Function.

    But Function::identity references the identity() method, which doesn't take any argument, an can thus not be used as a Function.

    Similarly, groupingBy() expects, as its second argument, an instance of Collector. Collectors.counting() returns a Collector. So you can use that. But Collector::counting references the counting() method, and a single method taking no argument is not sufficient at all to provide an implementation of the Collector interface, which has 5 methods.

    To make a car analogy, if you call a method expecting a vehicle, you can call garage.getCar() to get a Car and pass the returned Car as argument. But passing garage::getCarwould make no sense, because that would be "something that is able to give you a car". And that doesn't qualify as a Vehicle.