5

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))); 
0

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I got it. Thanks... Grouping By requires a Function as an argument, Whereas if I pass method reference, Method return type will be the argument ,which is not a function.... Thanks.
Nicely explained.+1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.