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

时间:2015-03-17 20:34:05

标签: java hashmap sum

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

我已经使用像这样的ArrayList完成了这个:

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

我有不同的对象与值权重,我试图将权重的总值返回为totalWeight,但似乎不能使用HashMap。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情

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

}