我有一个
的HashMaps列表OnClientClick="return OpenRadWindow('ImportSDS.aspx?id=', 'RWImport');"
我希望使用CODE作为java for loop等的关键字来获取总共TOTAL列的总数
即
遍历列表 对于每个键,显示总和(加在一起)总计
控制台输出应该是
1. Key/value key/Value
CODE=1 TOTAL=10
2. Key/value key/Value
CODE=1 TOTAL=10
3. Key/value key/Value
CODE=2 TOTAL=10
4. Key/value key/Value
CODE=2 TOTAL=10
5. Key/value key/Value
CODE=3 TOTAL=10
我尝试过使用
key with CODE 1 has total of 20 as sum
key with CODE 2 has total of 20 as sum
key with CODE 3 has total of 10 as sum
问题是只要CODE保持更改,循环就会运行正常,但是在最后一个代码值上,逻辑将不起作用:(该怎么办?
此致
艾登
答案 0 :(得分:1)
尝试使用Iterator
,如下所示:
int totale = 0;
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry tot = (Map.Entry)it.next();
totale += tot.getValue();
}
答案 1 :(得分:0)
在循环完成后,您似乎缺少的是输出最后一个总数:
int total = 0;
String previousCodeValue = "";
for(int i = 0; i < mapsList ; i++)
{
Map map = mapsList.get(i);
if(map.get("CODE") != previousCodeValue && !previousCodeValue.equals("") )
{
System.out.print(total);
total = 0;
}
previousCodeValue = map.get("CODE") ;
total = total + map.get("TOTAL")
}
System.out.print(total);
答案 2 :(得分:0)
因此,如果我理解正确,则需要所有地图上每个唯一KEY的TOTAL值的SUM。据说您可能希望在一次迭代中执行此操作,因此您需要随时跟踪唯一键和总计。下面我跟踪地图中的结果(是的,另一张地图,它只是一个例子)。
private static void main(String[] args) {
printResults(determineResults(createMaps()));
}
private static List<Map<String, Integer>> createMaps() {
List<Map<String, Integer>> maps = new ArrayList<>();
maps.add(createMap(1, 10));
maps.add(createMap(1, 10));
maps.add(createMap(2, 10));
maps.add(createMap(2, 10));
maps.add(createMap(3, 10));
return maps;
}
private static Map<String, Integer> createMap(int code, int total) {
Map<String, Integer> map = new HashMap<>();
map.put("CODE", code);
map.put("TOTAL", total);
return map;
}
private static Map<Integer, Integer> determineResults(List<Map<String, Integer>> maps) {
Map<Integer, Integer> results = new HashMap<>();
for(Map<String, Integer) map : maps) {
Integer key = map.get("CODE");
Integer sum = results.get(key);
if (sum == null) {
sum = 0;
}
Integer total = map.get("TOTAL");
sum += total;
results.put(key, sum);
}
return results;
}
private static void printResults(Map<Integer, Integer> results) {
for(Map.Entry<Integer, Integer> result : results) {
System.out.printf("key with CODE %s has total of %s as sum", result .getKey(), result.getValue());
}
}