问题描述
我想要列表< Pojo>
和返回
a Map< String ,List< Pojo>>
其中 Map
的键是 String
值在 Pojo
中,我们称之为字符串键
。
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 1: Key:a value:1
Pojo 2:Key :值: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< String,List< Pojo>>
with keySet()
大小为2,其中键a具有Pojos 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 lambdas来实现这一点?
How could I best achieve this using Java 8 lambdas?
推荐答案
似乎简单的 groupingBy
variant就是你所需要的:
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组列表进入映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!