Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing ArrayList object duplicates and getting sum of value

I have a list of a certain type of Object. I need to remove the duplicates object key field and sum up their values. It's kinda hard to explain so let me show you an example.

Say you have an Item class:

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;
   }

}

And you have a list of Item's:

List<Item> itemList = new ArrayList<Item>();

Populated as:

 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);

I need to have an output ArrayList that doesn't have duplicates, and adds up the quantity value.

So essentially, the result should be an arraylist of elements: mice, keyboards, monitors, cables where mice quantity = 35 (the sum), the keyboards quantity = 30, monitors = 4, cables = 50.

like image 403
GDell Avatar asked Jan 20 '26 16:01

GDell


2 Answers

Provided you are using Java 8, you can use Collectors#groupingBy:

itemList.stream().collect(
    Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQuantity)));
like image 73
Glorfindel Avatar answered Jan 23 '26 05:01

Glorfindel


use a HashMap:

HashMap<String, Integer> myItemMap = new HashMap<String,Integer>();
if(myItemMap.containsKey(item)
{
  int currentQty = myItemMap.get(item);
  myItemMap.get(item).setQuantity(qty + currentQty )
}
else
{
  myItemMap.put(item, qty);
}
like image 29
Micho Rizo Avatar answered Jan 23 '26 06:01

Micho Rizo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!