去除ArrayList对象中的重复项并获取值的总和

3
我可以帮忙翻译。以下是您需要翻译的内容:

我有一个特定类型对象的列表。我需要删除重复对象的键字段并汇总它们的值。很难解释,让我举个例子。

假设您有一个物品类:

public class Item {

protected String name;

protected int quantity;

public String getName() {
    return name;
   }

public void setName(String name) {
    this.name = name;
   }

public int getQuantity() {
    return quantity;
   }

public void setQuantity(intquantity) {
    this.quantity = quantity;
   }

}

而且您有一个 Item 列表:

List<Item> itemList = new ArrayList<Item>();

填充为:

 Item item1 = new Item();
 item1.setName("mice");
 item1.setQuantity(20);

 Item item2 = new Item();
 item2.setName("keyboards");
 item2.setQuantity(30);


 Item item3 = new Item();
 item3.setName("monitors");
 item3.setQuantity(4);

 Item item4 = new Item();
 item4.setName("mice");
 item4.setQuantity(15);

 Item item5 = new Item();
 item5.setName("cables");
 item5.setQuantity(50);


 itemList.add(0, item1);
 itemList.add(1, item2);
 itemList.add(2, item3);
 itemList.add(3, item4);
 itemList.add(4, item5);

我需要一个没有重复项且数量值相加的输出ArrayList。
因此,最终的结果应该是一个元素的arraylist:mice,keyboards,monitors,cables,其中鼠标数量= 35(总和),键盘数量= 30,显示器= 4,电缆= 50。

请展示您解决这个问题的尝试以及出了什么问题。在关系型数据库中,这似乎很容易 - 这将是一个带有“sum”聚合函数的分组查询。 - rgettman
我只需要逻辑上的帮助,不需要完整的答案。 - GDell
2个回答

5

如果您正在使用Java 8,您可以使用Collectors#groupingBy

itemList.stream().collect(
    Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQuantity)));

这看起来像是我需要的(按组分组)...但我没有使用Java 8 :( - GDell
1
升级的又一个理由 :) - Glorfindel

2

使用 HashMap:

HashMap<String, Integer> myItemMap = new HashMap<String,Integer>();
if(myItemMap.containsKey(item)
{
  int currentQty = myItemMap.get(item);
  myItemMap.get(item).setQuantity(qty + currentQty )
}
else
{
  myItemMap.put(item, qty);
}

现在尝试一下。我的最初假设是转换为哈希映射表。谢谢,我会告诉你的。 - GDell
如果您想继续使用您的Item对象,您也可以使用ArrayList,让我微调一下我的答案。 - Micho Rizo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接