簡體   English   中英

如何使用java流對作為HashMap值的ArrayList的元素求和?

[英]How to sum elements of an ArrayList which are values of a HashMap using java streams?

我有一個帶有整數和一些元素對象的 ArrayList 的 HashMap。 元素對象用價格和數量來描述。 我想遍歷每個 ArrayList 中的所有這些元素,通過調用每個元素element.price()總結它們,並創建一個新的 HashMap,其中包含代表每個數組列表總和的舊鍵和新值。 新哈希映射的鍵應保持不變。 嘗試使用流來做到這一點。

public static HashMap<Integer, Double> findIncomes(HashMap<Integer, ArrayList<Element>> mapa){


    Map<String, Double> m = mapa.entrySet().stream().flatMap()

    return m;
}

我想到的第一個解決方案是使用mapToDoublesum

那看起來像這樣:

public static HashMap<Integer, Double> findIncomes(HashMap<Integer, List<Element>> mapa) {
    HashMap<Integer, Double> sumsByKey = new HashMap<>();
    mapa.entrySet().stream().forEach(entry -> sumsByKey.put(entry.getKey(), entry.getValue().stream().mapToDouble(element -> element.getPrice()).sum()));
    return sumsByKey;
}

但是當總結 1.5d、5.4d 和 6.7d 時,結果是 13.600000000000001。

因此我必須記住:使用雙打進行計算時,通常最好使用BigDecimal

因此,更准確的解決方案可能如下所示:

public static HashMap<Integer, Double> findIncomes(HashMap<Integer, ArrayList<Element>> mapa){
    HashMap<Integer, Double> sumsByKey = new HashMap<>();
    mapa.entrySet().stream().forEach(entry -> sumsByKey.put(entry.getKey(),
        entry.getValue().stream().map(element -> BigDecimal.valueOf(element.getPrice())).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue()));
    return sumsByKey;
}

由於流中的流並不是真正可讀的,因此進一步重構它可能是有意義的。

你總是需要一張新地圖。 您不能使用不同類型更改同一地圖。 像這樣的東西可以完成這項工作,

public static HashMap<Integer, Double> findIncomes(HashMap<Integer, ArrayList<Element>> mapa) {

        final HashMap<Integer, Double> m = new HashMap<>();
        mapa.entrySet().stream().forEach(entry -> m.put(entry.getKey(), Double.valueOf(entry.getValue().stream().mapToDouble(Element::price).sum())));
        return m;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM