How to add an item only if no other items exist with the same name in the arraylist?

How would I go about only inserting an item if the item does not have the same name as the other items in the arraylist within my insertUniqueItem() method?

    public void insertUniqueItem()
    {

    }

    public static void main(String[] args)
    {
        ShoppingCart sc = new ShoppingCart();
        Item a = new Item("Kraft Cheese", 4, "\"Best Cheese in Town!\"");
        Item b = new Item("Bottle of Water", 2.50, "\"Refreshing Water!\"");

        sc.insertItem(a);
        sc.insertItem(b);

        sc.printInvoice();
        sc.insertUniqueItem();

        sc.print();

        DecimalFormat df = new DecimalFormat("#.00");

        System.out.println("Total Price: $" + df.format(sc.getTotal()));
    }
}
Jon Skeet
people
quotationmark

I would probably use a LinkedHashMap<String, Item> instead, where the key is the name of the item. That way:

  • You still get to preserve ordering
  • You can easily and efficiently check whether there's already an entry for a given item name.

You'd have something like:

if (!map.containsKey(item.getName()) {
    map.put(item.getName(), item);
}

This only works if you want all items to be unique in terms of name though. If you sometimes want to allow a duplicate name and sometimes not, you probably do want a list, and then you could have something like:

boolean containsItemName(ArrayList<Item> items, String name) {
    for (Item item : items) {
        if (item.getName().equals(name)) {
            return true;
        }
    }
    return false;
}

If you're using Java 8, you could use a stream-based solution:

boolean containsItemName(ArrayList<Item> items, String name) {
    return items.stream().anyMatch(item -> item.getName().equals(name));
}

people

See more on this question at Stackoverflow