How can I create a map from a list using java streams?

I want to create a list map using java8.

class Person {
    String name;
    int age;
    //etc
}

List<Person> persons;

Map<String, Person> personsByName = persons.stream().collect(
         Collectors.toMap(Person::getName, Functions.identify());

      

Result: The type Person does not define getName(T) that is applicable here

Why? What's wrong with Person::getName

?

+3


source to share


1 answer


If you have a method getName()

in Person

, this should be fine:

Map<String, Person> personsByName = persons.stream().collect(
                 Collectors.toMap(Person::getName, Function.identity()));

      



Note that I also changed Functions.identify()

(which does not exist) from Function.identity()

. I would guess it was your typo.

+4


source







All Articles