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

GDe*_*ell 3 java comparison arraylist

我有某种类型的对象的列表。我需要删除重复的对象键字段并总结它们的值。这有点难以解释,所以让我给你举个例子。

假设您有一个 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;
   }

}
Run Code Online (Sandbox Code Playgroud)

你有一个项目列表:

List<Item> itemList = new ArrayList<Item>();
Run Code Online (Sandbox Code Playgroud)

填充为:

 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);
Run Code Online (Sandbox Code Playgroud)

我需要一个没有重复项的输出 ArrayList,并将数量值相加。

因此,本质上,结果应该是一个元素数组列表:鼠标、键盘、显示器、电缆,其中鼠标数量 = 35(总和)、键盘数量 = 30、显示器 = 4、电缆 = 50。

Glo*_*del 5

如果您使用的是 Java 8,则可以使用Collectors#groupingBy

itemList.stream().collect(
    Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQuantity)));
Run Code Online (Sandbox Code Playgroud)