使用流从hashmap中获取值的总和 [英] Sum of values from hashmap using streams

查看:162
本文介绍了使用流从hashmap中获取值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an hashmap of huge size (around 10^60). I am putting values in each entry one by one. Problem is to get the sum of values from hashmap for given range of keys. eg: Putting it in simple Hashmap has entries from 0 to 1000 as a key and every key has an value(BigInteger). Now problem is to get sum of values from range (say) 37 to 95.

我曾经尝试过使用迭代器,但是当我们使用尺寸为10 ^ 60的巨大地图时,需要花费大量时间来操作索引.

I have tried with iterator but when we go for huge map of size 10^60, it is time taking operation for large range of indices.

我正在尝试使用流,但是作为流/parallelStream的新手,我对此并不了解.

I am trying it with streams but as am new to the streams/parallelStreams, I am not getting actual idea about it.

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.

I searched over SO and few are related to list or without Streams. Please also suggest if any improvement is possible like using some other data structure instead of HashMap.

推荐答案

您似乎正在寻找类似的东西:

You seem to be looking for something like :

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

或按照您的代码中的说明

or stated as in your code

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

这篇关于使用流从hashmap中获取值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆