删除重复的对象和求和字段值

时间:2015-08-13 14:18:27

标签: java loops arraylist iteration

我正在尝试从ArrayList中删除重复的对象,并对某个字段的值求和。例如:

如果我有ArrayList个对象"硬件":

{[Name: Ram, Quantity: 2], 
 [Name: Keyboard, Quantity: 3],
 [Name: Mouse, Quantity: 5],
 [Name: Keyboard, Quantity 5]} 

我想编写一个能找到重复数并将数量相加的函数。在这种情况下,键盘是重复的,因此最终的ArrayList应如下所示:

{[Name: Ram, Quantity: 2],
 [Name: Keyboard, Quantity: 8],
 [Name: Mouse, Quantity: 5]}.

我已经尝试过它,它似乎有时会起作用,但有时会错过元素。

    List<Hardware> myList = new ArrayList<Hardware>();
    myList.add(new Hardware("Ram", 2);
    myList.add(new Hardware("Keyboard", 3);
    myList.add(new Hardware("Mouse", 5);
    myList.add(new Hardware("Keyboard", 5);

    for(int i = 0; i < list.size(); i++){
         Hardware current = list.get(i);
        for(int j = 1; j < list.size(); j++){
            Hardware compare = list.get(j);
            if(current.getName().equals(compare.getName)){
                 current.setQuantity(current.getQuantity()
                                   + compare.getQuantity())
                 list.remove(compare);
             }
         }
    }

2 个答案:

答案 0 :(得分:5)

  • 如果您删除了该项目,则不希望增加j;它将导致您跳过紧接着的项目。
  • 您不希望在1启动第二个循环,您希望在i+1启动它,因为您不需要检查任何先前的元素。
  • 您的示例有一些语法错误,您将myList更改为list并且您缺少一些括号和分号

请改为尝试:

List<Hardware> list = new ArrayList<Hardware>();
list.add(new Hardware("Ram", 2));
list.add(new Hardware("Keyboard", 3));
list.add(new Hardware("Mouse", 5));
list.add(new Hardware("Keyboard", 5));
list.add(new Hardware("Mouse", 1));

for (int i = 0; i < list.size(); i++) {
  Hardware current = list.get(i);
  for (int j = i + 1; j < list.size(); j++) {
    Hardware compare = list.get(j);
    if (current.getName().equals(compare.getName())) {
      current.setQuantity(current.getQuantity() + compare.getQuantity());
      list.remove(compare);
      j--;
    }
  }
}

您还应该查看此链接,以帮助您解决以下问题:

答案 1 :(得分:2)

请注意你写了O(n * n)算法 仅当list.size()很小时,它才能正常工作。你可以在这里获得O(n)表现:

 Map<String, Hardware> hardwareMap = new HashMap<>();
 for(Hardware h : myList){
    Hardware current = hardwareMap.get(h.getName());
    if(current == null){
        hardwareMap.put(h.getName(), h);
    }else{
        current.setQuantity(current.getQuantity() + h.getQuantity());
    }
 }
 Collection<Hardware> list = hardwareMap.values();