可以在 HashMap 中总结对象值吗?

Possible to sum up object values in HashMap?

我刚开始在 Java 中使用 HashMap,我想知道是否可以在 HashMap 中汇总对象值。

我已经像这样使用 ArrayList 完成了此操作:

private int totalWeight() {
        int totalWeight = 0;
        for(Item item : items){
            totalWeight += item.getWeight();
        }
        return totalWeight;
    }

我有不同的对象具有权重值,我正在尝试 return 权重的总值作为 totalWeight,但使用 HashMap 似乎无法做到这一点。

你可以试试这样的

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;
    }

}