簡體   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