我正在尝试迭代arraylist。List<Map<String, Object>> majorList=new ArrayList<Map<String, Object>>();
数据格式为
{“ ledger”:“ A”,“ basicAmt”:10,“ excise”:2},
{“ ledger”:“ B”,“ exciseAmt”:20,“ grossAmt”:3},
{“ ledger”:“ A”,“ basicAmt”:30,“ excise”:5},
{“ ledger”:“ C”,“ exciseAmt”:50,“ grossAmt”:10},
{“ ledger”:“ B”,“ basicAmt”:40,“ excise”:8},
所需的结果将是:
{“ ledger”:“ A”,“ basicAmt”:40,“ excise”:7},
{“ ledger”:“ B”,“ exciseAmt”:60,“ grossAmt”:11},
{“ ledger”:“ C”,“ basicAmt”:50,“ excise”:10},
最佳答案
您将必须填充新的Map,然后将值添加到公共键上。总而言之,最好使用Map<String, Object>
,因为所有地图都将用于唯一分类帐。
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/