繁体   English   中英

使用流从hashmap中获取值的总和

[英]Sum of values from hashmap using streams

我有一个很大的哈希图(大约10 ^ 60)。 我正在每个条目中逐一输入值。 问题是从给定键范围的哈希映射中获取值的总和。 例如:将其放在简单的Hashmap中,键的输入范围为0到1000,每个键都有一个值(BigInteger)。 现在的问题是要获取值的总和(范围为37到95)。

我已经尝试过使用迭代器,但是当我们使用尺寸为10 ^ 60的巨大地图时,是时候对大量索引进行操作了。

我正在尝试使用流,但是作为streams / 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM