[英]Java 8 stream - Merge maps and calculate average of “values”
Let's say I have a List
of classes that each has a Map
. 假设我有一个类
List
,每个类都有一个Map
。
public class Test {
public Map<Long, Integer> map;
}
the Long
keys in the Map
are timestamps and the Integer
values are scores. Map
中的Long
键是时间戳, Integer
值是得分。
I am trying to create a Stream
that can combine the maps from all objects and output a Map
with the unique Timestamps (The Long
s) and an average score. 我正在尝试创建一个
Stream
,它可以组合来自所有对象的Map
,并输出具有唯一时间戳(The Long
s)和平均分数的Map
。
I have this code, but it gives me the sum of all the scores and not the average (The Integer
class doesn't have an average method). 我有这个代码,但它给了我所有分数的总和而不是平均值 (
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);
I'm thinking that this might not be an easy problem so solve in a single Stream
, so an output with a Map
with the unique timestamps and a List
of all the scores would also be fine. 我认为这可能不是一个简单的问题所以在一个
Stream
解决,所以带有唯一时间戳的Map
和所有分数的List
的输出也可以。 Then I can calculate the average myself. 然后我可以自己计算平均值。
Map<Long, List<Integer>>
It it possible? 有可能吗?
Instead of Collectors.toMap
use Collectors.groupingBy
: 而不是
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)
)
);
Oh, and even though you probably don't need it anymore, you can get the Map<Long, List<Integer>>
you asked about in the last part of your question just as easily: 哦,即使你可能不再需要它,你也可以轻松获得你在问题的最后部分询问的
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.