[英]Java 8 stream - Merge maps and calculate average of “values”
假设我有一个类List
,每个类都有一个Map
。
public class Test {
public Map<Long, Integer> map;
}
Map
中的Long
键是时间戳, Integer
值是得分。
我正在尝试创建一个Stream
,它可以组合来自所有对象的Map
,并输出具有唯一时间戳(The Long
s)和平均分数的Map
。
我有这个代码,但它给了我所有分数的总和而不是平均值 ( Integer
类没有平均方法)。
Test test1 = new Test();
test1.map = new HashMap() {{
put(1000L, 1);
put(2000L, 2);
put(3000L, 3);
}};
Test test2 = new Test();
test2.map = new HashMap() {{
put(1000L, 10);
put(2000L, 20);
put(3000L, 30);
}};
List<Test> tests = new ArrayList() {{
add(test1);
add(test2);
}};
Map<Long, Integer> merged = tests.stream()
.map(test -> test.map)
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
Integer::sum
)
);
System.out.println(merged);
我认为这可能不是一个简单的问题所以在一个Stream
解决,所以带有唯一时间戳的Map
和所有分数的List
的输出也可以。 然后我可以自己计算平均值。
Map<Long, List<Integer>>
有可能吗?
而不是Collectors.toMap
使用Collectors.groupingBy
:
Map<Long, Double> merged = tests.stream()
.map(test -> test.map)
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.averagingInt(Map.Entry::getValue)
)
);
哦,即使你可能不再需要它,你也可以轻松获得你在问题的最后部分询问的Map<Long, List<Integer>>
:
Map<Long, List<Integer>> merged = tests.stream()
.map(test -> test.map)
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.