membersound
membersound

Reputation: 86925

How to create a map from list with java-streams?

I want to create a Map of a List with 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 is wrong with Person::getName?

Upvotes: 4

Views: 1581

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

If you have a getName() method in Person, this should be fine:

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

Note that I've also changed Functions.identify() (which doesn't exist) with Function.identity(). I would assume it was a typo of yours.

Upvotes: 6

Related Questions