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

标签 java arraylist comparison

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

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

相关文章:

java - 静态与静态Java 中的动态绑定(bind)

java - JFileChooser 不允许选择目录

java - 如何将 Collection<Collection<Double>> 转换为 List<List<Double>>?

Java - ArrayList<> 和 LinkedList<> - 作为标识符的类

c# - 比较两个频谱图以找到它们匹配算法的偏移量

version-control - 什么时候 TAG 应该优先于 BRANCHING,反之亦然(在 CVS 中)?

Javascript:比较由 javascript 设置的 backgroundColor

java - 将对象的引用传递给 null JAVA 后使用接口(interface)

java - 无法添加到由对象组成的私有(private) ArrayList 属性

java - GUI 在调整大小或最小化之前不显示内容