Java 8 lambdas 将列表分组到映射中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30755949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:07:17  来源:igfitidea点击:

Java 8 lambdas group list into map

javajava-8java-stream

提问by Robert Bain

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

我想取 aList<Pojo>returna Map<String, List<Pojo>>,其中Map的键是 中的一个StringPojo,我们称之为String key

To clarify, given the following:

为了澄清,鉴于以下内容:

Pojo 1: Key:a value:1

Pojo 1:键:一个值:1

Pojo 2: Key:a value:2

Pojo 2:键:一个值:2

Pojo 3: Key:b value:3

Pojo 3:键:b 值:3

Pojo 4: Key:b value:4

Pojo 4:键:b 值: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.

我想要一个Map<String, List<Pojo>>keySet()大小的2,其中键“a”具有的POJO 1和2,和键“b”具有的POJO 3和4。

How could I best achieve this using Java 8 lambdas?

我怎样才能最好地使用 Java 8 lambdas 实现这一点?

采纳答案by Eran

It seems that the simple groupingByvariant is what you need :

似乎简单的groupingBy变体正是您所需要的:

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

回答by cristianoms

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:

此外,如果您想返回一个类似的地图,但您希望地图的值是 Pojo 的某个属性而不是整个 Pojo,您可以这样做:

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