gpt4 book ai didi

java - 从 map 数组列表中获取唯一名称和相应的金额总和

转载 作者:太空宇宙 更新时间:2023-11-04 14:01:36 26 4
gpt4 key购买 nike

我正在尝试迭代数组列表。 List<Map<String, Object>> majorList=new ArrayList<Map<String, Object>>();

数据格式为

  1. {"ledger": "A","basicAmt": 10,"消费税": 2},{"ledger": "B","exciseAmt": 20,"grossAmt": 3}, {"ledger": "A","basicAmt": 30,"消费税": 5},{"ledger": "C","exciseAmt": 50,"grossAmt": 10},{“ledger”:“B”,“basicAmt”:40,“消费税”:8},

    所需的结果如下:

  2. {"ledger": "A","basicAmt": 40,"消费税": 7},{"ledger": "B","exciseAmt": 60,"grossAmt": 11},{"ledger": "C","basicAmt": 50,"消费税": 10},

最佳答案

您必须填充一个新的映射,然后根据公共(public)键添加值。总结后最好有一个 Map<String, Object>因为所有 map 都将用于唯一的分类帐。

    Map<String, Map<String, Object>> sumMap = new HashMap<String, Map<String,Object>>();
for (Map<String, Object> abc : majorList) {
Map temp = sumMap.get((String) abc.get("ledger"));
if (temp == null) {
sumMap.put((String) abc.get("ledger"), abc);
} else {
for (Entry<String, Object> entry : abc.entrySet()) {
if (!entry.getKey().equals("ledger")) {
temp.put(entry.getKey(),
(Integer) temp.get(entry.getKey())
+ (Integer) entry.getValue());
}
}
}
}

关于java - 从 map 数组列表中获取唯一名称和相应的金额总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29252678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com