【问题标题】:Possible to sum up object values in HashMap? [duplicate]可以总结HashMap中的对象值吗? [复制]
【发布时间】:2015-05-20 11:24:43
【问题描述】:

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

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

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

我有不同的对象的值权重,我试图将权重的总值作为 totalWeight 返回,但似乎无法使用 HashMap 这样做。

【问题讨论】:

  • 你能告诉我们你想在哪里使用地图吗?
  • 使用map.values() 获取值,然后像执行列表一样遍历它们

标签: java hashmap sum


【解决方案1】:

你可以试试这样的

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

}

【讨论】:

  • 这似乎工作得很好!非常感谢!!
猜你喜欢
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多