ineedmoney
ineedmoney

Reputation: 63

How to remove duplicated items from an ArrayList based on quantity

First an arraylist with items is created

ArrayList<Item> Items

Note: item has attribute quantity. Then, the user will be asked to input the item's name and quantity to be dropped. However, if more than one item with same name appears in the list, the quantity should be added together. For example, if the list contains "Apple" (quantity 5) and "Apple" (quantity 3), and the user wishes to remove 7 apples from the item list, all the first "Apple" with quantity 5 will be dropped and the second "Apple" will become 1 after dropping. It will be removed once quantity=0

What is the appropriate approach to solve this?

Upvotes: 0

Views: 77

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19565

  • Check if the total amount of quantities is sufficient in the list
  • Iterate the list to find an item by name.
  • When found, decrease the item's quantity by the input quantity to drop -- if the item's quantity gets equal to zero or below, remove the item from the list. Also decrease the input quantity by the item's quantity and break out of the loop as soon as no remaining quantity is available.
public void removeNameQuantity(String name, int q) {

    int totalQ = Items.stream()
            .filter(i -> name.equals(i.getName()))
            .mapToInt(Item::getQuantity)
            .sum();
    if (totalQ < q) {
        System.out.println("Insufficient quantity of " + name + "(s) available");
        return;
        // or throw some appropriate exception
    }
    for (Iterator<Item> it = Items.iterator(); it.hasNext() && q > 0;) {
        Item item = it.next();
        if (name.equals(item.getName())) {
            int iq = item.getQuantity();
            item.setQuantity(iq - Math.min(q, iq));
            if (iq <= q) {
                it.remove();
            }
            q -= iq;
        }
    }
}

Upvotes: 2

Related Questions