Search code examples
javalistlambdahashmapjava-stream

Method reference expression is not expected here, compile time error


I am using stream to iterate through the list and want to collect it in the map but getting compile time error:

Method reference expression is not expected here

Here is my code

List<Person> personList = getPersons();
Map<String, Integer> personAgeMap = personList.stream()
       .collect(Collectors.toMap(Person::getFirstName + "_" + Person::getLastName, Person::getAge));

I have checked these answers:

but these are not what i am looking for, also i have seen the method reference type.

In this case it is instance method of instance type, how can i have instance of Person in the collectors.

what could be the possible solution or is it even doable this way?


Solution

  • You can't use a method reference in there. Try a lambda instead.

    Collectors.toMap(
        p -> String.format("%s_%s", p.getFirstName(), p.getLastName()), 
        Person::getAge
    )
    

    Both Person::getFirstName and Person::getLastName are instances of some functional interface (never of String), for example Supplier<String> or Function<Person, String>, and the operator + can't be applied to them.

    Similarly, it wouldn't make much sense, if you were

    Object o = new Object() + new Object();
    

    To puzzle you a bit

    p -> ((Function<Person, String>) Person::getFirstName).apply(p) + "_" + 
         ((Function<Person, String>) Person::getLastName).apply(p)