我有一个特定类型对象的列表。我需要删除重复的对象键字段并总结它们的值。这有点难以解释,所以让我举个例子。
假设您有一个 Item 类:
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>();
填充为:
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,并将数量值相加。
本质上,结果应该是一个元素数组列表:鼠标、键盘、显示器、电缆,其中鼠标数量 = 35(总和)、键盘数量 = 30、显示器 = 4、电缆 = 50。
最佳答案
如果您使用的是 Java 8,则可以使用 Collectors#groupingBy :
itemList.stream().collect(
Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQuantity)));
关于java - 删除ArrayList对象的重复项并获取值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31710598/