Java 删除重复的ArrayList对象并获取值之和
我有一个特定类型对象的列表。我需要删除duplicates对象键字段并汇总它们的值。这有点难以解释,所以让我给你举个例子 假设您有一个Item类:Java 删除重复的ArrayList对象并获取值之和,java,arraylist,comparison,Java,Arraylist,Comparison,我有一个特定类型对象的列表。我需要删除duplicates对象键字段并汇总它们的值。这有点难以解释,所以让我给你举个例子 假设您有一个Item类: public class Item { protected String name; protected int quantity; public String getName() { return name; } public void setName(String name) { this.name = name;
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;
}
}
您有一个项目列表:
List<Item> itemList = new ArrayList<Item>();
我需要一个没有重复项的输出ArrayList,并将数量值相加
因此,基本上,结果应该是元素的数组列表:鼠标、键盘、监视器、电缆,其中鼠标数量=35(总和),键盘数量=30,监视器=4,电缆=50。如果您使用的是Java 8,您可以使用: 使用哈希映射:
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);
}
HashMap myItemMap=newhashmap();
if(myItemMap.containsKey(项目)
{
int currentQty=myItemMap.get(项目);
myItemMap.get(item).setQuantity(数量+当前数量)
}
其他的
{
myItemMap.put(项目、数量);
}
请展示您解决此问题的尝试以及出现的问题。这看起来在RDBMS中很容易做到-这将是一个带有“sum”的分组查询聚合函数。不要求完整的答案,我只需要逻辑方面的帮助-现在试一试。我最初的假设是转换为hashmap。谢谢,我会让你知道如果你想继续使用Item对象,你也可以使用ArrayList,让我调整我的答案这看起来像我需要的(分组依据)…但我没有使用Java 8:(升级的另一个原因:)
itemList.stream().collect(
Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQuantity)));
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);
}