Java 可以在HashMap中汇总对象值吗?
我刚刚开始在Java中使用HashMaps,我想知道是否可以在HashMap中汇总对象值 我已经使用ArrayList这样做了:Java 可以在HashMap中汇总对象值吗?,java,hashmap,sum,Java,Hashmap,Sum,我刚刚开始在Java中使用HashMaps,我想知道是否可以在HashMap中汇总对象值 我已经使用ArrayList这样做了: private int totalWeight() { int totalWeight = 0; for(Item item : items){ totalWeight += item.getWeight(); } return totalWeight; } 我有不同的对
private int totalWeight() {
int totalWeight = 0;
for(Item item : items){
totalWeight += item.getWeight();
}
return totalWeight;
}
我有不同的对象,它们的值为weight,我试图将weight的总值返回为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;
}
}
公共类HMTest{
公共静态void main(字符串[]args){
整数总权重=0;
HashMap=newHashMap();
地图放置(“键1”,新项目(10));
地图放置(“键2”,新项目(20));
地图放置(“键3”,新项目(30));
集合值=map.values();
(第一项:价值){
totalWeight+=i.getWeight();
}
System.out.println(“总重量:+总重量”);
}
}
类项目{
私有整数权重;
公共物品(整重){
重量=重量;
}
公共整数getWeight(){
返回重量;
}
公共空隙设定重量(内部重量){
重量=重量;
}
}
你能给我们看一个你试图使用映射的片段吗?使用map.values()
抓取值,然后像你做列表一样循环它们。这看起来很好!谢谢!!