将所有的人的数量我有一个Person类用相同的ID从HashMap中
public class Person {
private int id;
private int amount;
public Person(int id, int amount){
this.id = id;
this.amount = amount;
}
//getters
}
而且我有一个mainClass这样
Map<String, Person> mapOfObjects = new HashMap<String, Person>();
mapOfObjects.put("map1", new Person(1, 1000));
mapOfObjects.put("map2", new Person(1, 1000));
mapOfObjects.put("map3", new Person(1, 1000));
mapOfObjects.put("map4", new Person(2, 1000));
mapOfObjects.put("map5", new Person(2, 1000));
mapOfObjects.put("map6", new Person(3, 1000));
Map<Integer, Integer> mapOfSum = new HashMap<Integer, Integer>();
int sum = 0;
List list = new LinkedList(mapOfObjects.keySet());
for (int i = 0; i < mapOfObjects.size(); i++) {
for (int j = 1; j < mapOfObjects.size() - i; j++) {
if (mapOfObjects.get(list.get(i)).getId() ==
mapOfObjects.get(list.get(j)).getId()) {
sum += (mapOfObjects.get(list.get(i)).getAmount() +
mapOfObjects.get(list.get(j)).getAmount());
}
mapOfSum.put(mapOfObjects.get(list.get(i)).getId(), sum);
}
}
System.out.println(mapOfSum);
它给我的输出:
{1=8000, 2=8000, 3=0}
但我想要这样的东西
id=1 amount =3000, id =2 amount = 2000, id =3 amount =1000
如何从它的总和,同时运行的第一个for循环
你的问题不明确。请尝试解释你正在努力做的更好 – amit 2014-09-04 10:17:45
循环内部的'if'可能是错误的,你总是比较'mapOfObjects.get(list.get(i))。getId()'和它自己。 – usr2564301 2014-09-04 10:18:45
我想添加所有金额相同的人 – Sarbong 2014-09-04 10:19:22