有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用流从hashmap获得的值之和

我有一个巨大的hashmap(大约10^60)。 我在每个条目中逐个输入值。 问题是从hashmap中获取给定范围键的值之和。 如: 简单地说 Hashmap有0到1000个条目作为一个键,每个键都有一个值(BigInteger)。 现在的问题是得到范围(比如)37到95之间的值的总和

我试过使用迭代器,但当我们使用10^60大小的大型映射时,对于大范围的索引来说,这是一个耗时的操作

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

我搜索了这么多,很少有和列表相关或没有流的。还请建议是否有任何改进,如使用其他数据结构而不是HashMap


共 (1) 个答案

  1. # 1 楼答案

    您似乎正在寻找以下内容:

    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();