gpt4 book ai didi

java - 使用流的 hashmap 的值总和

转载 作者:行者123 更新时间:2023-11-30 07:41:33 25 4
gpt4 key购买 nike

我有一个巨大的 HashMap (大约 10^60)。我将值一一放入每个条目中。问题是针对给定的键范围从 HashMap 中获取值的总和。例如:简单来说Hashmap 具有从 0 到 1000 的条目作为键,每个键都有一个值(BigInteger)。现在的问题是获取 37 到 95 范围内的值的总和。

我尝试过使用迭代器,但是当我们使用 10^60 大小的巨大 map 时,需要对大范围的索引进行操作。

我正在尝试使用流,但作为流/parallelStreams 的新手,我并没有真正了解它。

BigInteger index1 = new BigInteger(array[1]); // array[1] min value
BigInteger index2 = new BigInteger(array[2]); // array[2] max value
BigInteger max = index1.max(index2); // getting max and min range from index1 and index2
BigInteger min = index1.min(index2);
AtomicReference<Long> atomicSum = new AtomicReference<Long>(0l);
hashMap.entrySet().parallelStream().
forEach(e -> {
if (e.getKey().compareTo(min) == 1 && e.getKey().compareTo(max) == -1) {
atomicSum.accumulateAndGet(e.getValue().longValue(), (x,y) -> x+y);
}
});

我搜索过 SO,很少有与列表或没有 Streams 相关的。还请建议是否可以进行任何改进,例如使用其他数据结构而不是 HashMap。

最佳答案

你似乎在寻找类似的东西:

BigInteger sumOfValues = hashMap.entrySet().stream()
.filter(e -> e.getKey().compareTo(min) > 0 && e.getKey().compareTo(max) < 0)
.map((Map.Entry::getValue))
.reduce(BigInteger.ZERO, BigInteger::add);

或如您的代码中所述

Long sumOfValues = hashMap.entrySet().stream()
.filter(e -> e.getKey().compareTo(min) > 0 && e.getKey().compareTo(max) < 0)
.map((Map.Entry::getValue))
.reduce(BigInteger.ZERO, BigInteger::add).longValue();

关于java - 使用流的 hashmap 的值总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55888405/

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