Java 8: Map of field to list of items

时间:2017-08-04 13:16:33

标签: java filter java-8 mapping java-stream

Lets say I have a List<Person> Gathering and I want a Map<String, List<Person>>, mapping Person.surname to a List of Person:s that have the same surname. Is there a convenient way to do this using streams?

1 个答案:

答案 0 :(得分:4)

是的,使用Collectors.groupingBy(...)

Map<String, List<Person>> personsBySurname = gathering.stream()
        .collect(Collectors.groupingBy(Person::get‌​Surname));