【问题标题】:Get cumulative value from a List of Map<String, Integer>从 Map<String, Integer> 列表中获取累积值
【发布时间】:2013-12-01 13:22:34
【问题描述】:

我有一个 ListMap&lt;String, Integer&gt; 。每个Map 实例都包含productName 作为key,product price 作为value。

List<Map<String, Integer>> products = GET_ALL_PRODUCTS();

例如,列表可能包含具有以下数据的地图:

地图 1:

"prod1" : 10
"prod2" : 5
"prod3" : 2

地图2:

"prod3" : 3
"prod4" : 6

地图 3:

"prod1" : 12
"prod4" : 8

我需要生成一个新的Map&lt;String, Integer&gt;,其中仍包含 productName 作为键,但每个产品的累计价格金额作为值。那就是:

新地图应包含:

"prod1" : 10+12
"prod2" : 5
"prod3" : 2+3
"prod4" : 6+8

我最终得到了以下代码,我想知道生成这个新的Map最有效的方法是什么?

Map<String, Integer> cumulativeMap = new HashMap<String, Integer>();
for(int i=0; i< products.size(); i++){
    Map<String, Integer> product = products.get(i);
    ...
}

【问题讨论】:

    标签: java performance jakarta-ee map


    【解决方案1】:

    试试,

    List<Map<String, Integer>> products = new ArrayList<>();
    //Add products Maps here 
    
    Map<String, Integer> cumulativeMap = new HashMap<String, Integer>();
    // Use enhaced for loop for efficiency.
    for(Map<String, Integer> productMap: products){
      for(Map.Entry<String, Integer> p: productMap.entrySet()){
    
       if(cumulativeMap.containsKey(p.getKey())){
          cumulativeMap.put(p.getKey(), cumulativeMap.get(p.getKey())+ p.getValue());
       }
       else{
         cumulativeMap.put(p.getKey(),  p.getValue());
       }
      }
    } 
    

    【讨论】:

    • 是否比基于索引的循环更高效?
    • 你应该避免在循环中调用get @aga。应该首选使用Map.Entry&lt;K,V&gt;
    • 不,它并不比基于索引的循环更有效,除非ListLinkedList 或类似的东西。 ArrayList 实现了RandomAccessList,因此索引访问必须更快根据定义。但是,差异很可能可以忽略不计。并且使用 for-each 循环更具可读性。
    • @aga, see this.
    • @aga:不,HashMap.get 的时间复杂度是 O(1),假设 hashCode 运行良好。仅在病理情况下,它可能会变得像 O(N) 一样糟糕。但是,使用 entrySet 可以保存访问权限。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多