按Java 8中的Map列表分组 [英] Grouping by List of Map in Java 8
本文介绍了按Java 8中的Map列表分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表:
List<Map<String, Long>>
有没有办法,使用lambda将此列表转换为:
Is there a way, using lambda, to convert this list to:
Map<String, List<Long>>
示例:
Map<String, Long> m1 = new HashMap<>();
m1.put("A", 1);
m1.put("B", 100);
Map<String, Long> m2 = new HashMap<>();
m2.put("A", 10);
m2.put("B", 20);
m2.put("C", 100);
List<Map<String, Long>> beforeFormatting = new ArrayList<>();
beforeFormatting.add(m1);
beforeFormatting.add(m2);
格式化后:
Map<String, List<Long>> afterFormatting;
看起来像:
A -> [1, 10]
B -> [100, 20]
C -> [100]
推荐答案
你需要 flatMap
每个Map的条目集,用于创建 Stream< Map.Entry< String,Long>>
。然后,可以使用 groupingBy(分类器,下游)
collector:分类器返回条目的键并且下游收集器将条目映射到其值并将其收集到列表
。
You need to flatMap
the entry set of each Map to create a Stream<Map.Entry<String, Long>>
. Then, this Stream can be collected with the groupingBy(classifier, downstream)
collector: the classifier returns the key of the entry and the downstream collector maps the entry to its value and collects that into a List
.
Map<String, List<Long>> map =
list.stream()
.flatMap(m -> m.entrySet().stream())
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
此代码需要以下静态导入:
This code needs the following static imports:
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
完整示例:
public static void main(String[] args) {
Map<String, Long> m1 = new HashMap<>();
m1.put("A", 1l);
m1.put("B", 100l);
Map<String, Long> m2 = new HashMap<>();
m2.put("A", 10l);
m2.put("B", 20l);
m2.put("C", 100l);
List<Map<String, Long>> beforeFormatting = new ArrayList<>();
beforeFormatting.add(m1);
beforeFormatting.add(m2);
Map<String, List<Long>> afterFormatting =
beforeFormatting.stream()
.flatMap(m -> m.entrySet().stream())
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
System.out.println(afterFormatting); // prints {A=[1, 10], B=[100, 20], C=[100]}
}
这篇关于按Java 8中的Map列表分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文