gpt4 book ai didi

Java 8 流 - 合并映射并计算 "values"的平均值

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:21 27 4
gpt4 key购买 nike

假设我有一个 List 类,每个类都有一个 Map

public class Test {
public Map<Long, Integer> map;
}

Map 中的 Long 键是时间戳,Integer 值是分数。

我正在尝试创建一个 Stream,它可以组合来自所有对象的映射并输出一个具有唯一时间戳(Long)的 Map s) 和平均分。

我有这段代码,但它给出了所有分数的总和,而不是平均值(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())
)
);

关于Java 8 流 - 合并映射并计算 "values"的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47569933/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com