Java 8 lambdas 将列表分组到映射中 [英] Java 8 lambdas group list into map
问题描述
我想要一个 List
和 return
一个 Map
其中 Map
的key是Pojo
中的一个String
值,我们称之为String key
.
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:键:一个值:1
Pojo 1: Key:a value:1
Pojo 2:键:一个值:2
Pojo 2: Key:a value:2
Pojo 3:键:b 值:3
Pojo 3: Key:b value:3
Pojo 4:键:b 值:4
Pojo 4: Key:b value:4
我想要一个 Map
,keySet()
大小为 2,其中键a"有 Pojo 1 和 2,键b"有 pojos 3 和 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.
我怎样才能最好地使用 Java 8 lambda 实现这一点?
How could I best achieve this using Java 8 lambdas?
推荐答案
看来简单的 groupingBy
变体正是您所需要的:
It seems that the simple groupingBy
variant is what you need :
Map<String, List<Pojo>> map = pojos.stream().collect(Collectors.groupingBy(Pojo::getKey));
这篇关于Java 8 lambdas 将列表分组到映射中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!