Java 8 lambdas group list into map

时光总嘲笑我的痴心妄想 提交于 2020-01-08 17:13:10

问题


I want to take a List<Pojo> and return a Map<String, List<Pojo>> where the Map's key is a String value in Pojo, let's call it String key.

To clarify, given the following:

Pojo 1: Key:a value:1

Pojo 2: Key:a value:2

Pojo 3: Key:b value:3

Pojo 4: Key:b value:4

I want a Map<String, List<Pojo>> with keySet() sized 2, where key "a" has Pojos 1 and 2, and key "b" has pojos 3 and 4.

How could I best achieve this using Java 8 lambdas?


回答1:


It seems that the simple groupingBy variant is what you need :

Map<String, List<Pojo>> map = pojos.stream().collect(Collectors.groupingBy(Pojo::getKey));



回答2:


Also, if you wanted to return a similar map but instead of whole Pojo you wanted the map's values be some property of the Pojo, you would do like that:

Map<String, List<String>> map = pojos.stream()
            .collect(
                    Collectors.groupingBy(
                            Employee::getKey, Collectors.mapping(
                                    Pojo::getSomeStringProperty, Collectors.toList())));


来源:https://stackoverflow.com/questions/30755949/java-8-lambdas-group-list-into-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!