我正在尝试从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);
}
}
}
答案 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();