gpt4 book ai didi

java - 如何将 List>> 转换为 Map>

转载 作者:行者123 更新时间:2023-11-30 08:14:58 25 4
gpt4 key购买 nike

我遇到了 java8 流问题。
我有一个

List<Map<Customer, Map<key, BigDecimal>>> 

我想变成一个

Map<Customer, Map<key, BigDecimal>> 

其中键是月份,BigDecimal 是 BigDecimals 的总和。

我可以通过迭代来完成,但我想使用 java8 流,因为我认为这应该是可能的。
当我迭代时,我正在使用一个临时的

Map<Customer, List<Map<key, BigDecimal>>>

我通过对每个客户的迭代来减少。

但是要用流来做,我不得不将元素添加到临时列表中!

有人可以帮忙吗?

最佳答案

在 Java 9 中,我们将获得 flatMapping 收集器 (see here),这将使这类事情变得更简单。

您可以将 flatMapping 的代码反向移植到您的项目中,当 java 9 出现时,将静态导入替换为官方导入。它看起来像这样:

public static <T, U, A, R>
Collector<T, ?, R> flatMapping(
Function<? super T, ? extends Stream<? extends U>> mapper,
Collector<? super U, A, R> downstream
) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
return Collector.of(
downstream.supplier(),
(r, t) -> {
try (Stream<? extends U> result = mapper.apply(t)) {
if (result != null) {
result.sequential()
.forEach(u -> downstreamAccumulator.accept(r, u));
}
}
},
downstream.combiner(), downstream.finisher(),
downstream.characteristics().toArray(new Collector.Characteristics[0])
);
}

然后你会像这样使用它:

Map<Customer, Map<key, BigDecimal>> result = input.stream()
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(groupingBy(
e->e.getKey(),
flatMapping(
e->e.getValue().entrySet().stream(),
toMap(e->e.getKey(), e->e.getValue(), BigDecimal::add)
)
));

如果您不想这样做并且更愿意使用当前的标准收集器,您可以使用 3 参数 toMap,它结合了 map 和 reduce:

Map<Customer, Map<key, BigDecimal>> result = input.stream()
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(toMap(
e->e.getKey(),
e->e.getValue(),
(a,b) -> Stream.of(a,b) // merge the 2 maps
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(toMap(
e->e.getKey(),
e->e.getValue(),
BigDecimal::add
))
))

关于java - 如何将 List<Map<Customer, Map<key, BigDecimal>>> 转换为 Map<Customer, Map<key, BigDecimal>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207999/

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