java - 从 Map<String, Integer> 列表中获取累积值

标签 java performance jakarta-ee map

我有一个 ListMap<String, Integer> .每个Map实例包含产品名称作为键,产品价格作为值。

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

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

map 1:

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

map 2:

"prod3" : 3
"prod4" : 6

map 3:

"prod1" : 12
"prod4" : 8

我需要生成一个新的 Map<String, Integer>其中仍然包含 productName 作为键,但每个产品的累计价格作为值。即:

新 map 应该包含:

"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);
    ...
}

最佳答案

尝试,

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

关于java - 从 Map<String, Integer> 列表中获取累积值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20047009/

相关文章:

php - 对 PHP 脚本开销的内部 Apache 请求

java - RabbitMQ 对 EC2 性能的挑战

java - java代码中的getParameter()怎么办?

java - 主类 JFrame 中另一个类的 JPanel 大小问题

java - DDD 中的聚合对象

java - Google App Engine 本地数据存储查看器无法正常工作?

java - 在n个竞争对手的比赛中安排k个位置

java - 如何在我的 JAVA tomcat Web 应用程序中阻止 El-Tags

java - 父类(super class)子类实例化

javascript - WeakMap 性能是否受 Key Object 影响?