What collection do I need to store an Object and it's quantity?

Viewed 124

I need to store the Product (Object), and it's quantity in a Collection, where I will be able to increase the quantity of each product whenever needed.

What Collection type will work and is best to use in this case?

2 Answers

I would use a Map, for example a HashMap. The map key should be the key of the product and the value is the quantity of the product.

If the quantity is simply a count, and if you're open to using a third-party library, you could use a Bag from Eclipse Collections. A Bag is a Collection that is unordered and allows duplicates. Internally, a HashBag is usually implemented with a HashMap, with keys associated to their counts. In the case of HashBag in Eclipse Collections, the backing store is an ObjectIntHashMap. This has the advantage of not having to box and unbox the Integer objects as you might if you map keys to their counts in a java.util.HashMap.

Product product1 = Product.of("abc");
Product product2 = Product.of("xyz");

MutableBag<Product> counts = Bags.mutable.empty();

counts.addOccurrences(product1, 5);
counts.addOccurrences(product2, 10);

Assert.assertEquals(5, counts.occurrencesOf(product1));
Assert.assertEquals(10, counts.occurrencesOf(product2));

Here is a blog that describes Bag in more detail.

Note: I am a committer for Eclipse Collections

Related