4

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.

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

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.

Wangensteen
  • 75
  • 1
  • 6

1 Answers1

0

You can try something like this

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

}
Ved Agarwal
  • 565
  • 3
  • 6
  • 14