Possible to sum up object values in HashMap?
本问题已经有最佳答案,请猛点这里访问。
我刚刚开始在Java中使用哈希图,我想知道是否可以总结哈希图中的对象值。
我已经使用类似这样的数组列表完成了这项工作:
1 2 3 4 5 6 7 | private int totalWeight() { int totalWeight = 0; for(Item item : items){ totalWeight += item.getWeight(); } return totalWeight; } |
我有不同的具有值权重的对象,我正试图将权重的总值返回为total weight,但似乎无法使用hashmap执行此操作。
你可以试试这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public class HMTest { public static void main(String[] args) { int totalWeight = 0; HashMap<String, Item> map = new HashMap<String, Item>(); map.put("Key1", new Item(10)); map.put("Key2", new Item(20)); map.put("Key3", new Item(30)); Collection<Item> values = map.values(); for (Item i : values) { totalWeight += i.getWeight(); } System.out.println("Total Weight :" + totalWeight); } } class Item { private int weight; public Item(int weight) { this.weight = weight; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } } |