本文介绍了可以总结HashMap中的对象值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've just started using HashMaps in Java, and I was wondering if it's possible to sum up the object values in the HashMap.

我已经使用ArrayList完成了这项工作:

I've already done this using an ArrayList like so:

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

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

I have different objects with the value weight, and I'm trying to return the total value of the weight as totalWeight, but can't seem to do so using 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;
    }

}

这篇关于可以总结HashMap中的对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 08:31