Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 985
membersound Avatar asked Sep 13 '25 14:09

membersound


1 Answers

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.

like image 174
Konstantin Yovkov Avatar answered Sep 16 '25 05:09

Konstantin Yovkov