Reputation: 76
I'm currently working on one project. I am trying to create a management system for a store. The problem is I need some sort of collection for stock, where while adding elements that already exist with the same name (updating the number of same item) it's state (attribute stockLevel) would update accordingly to the given quantity. Does anyone know which should be the best to let do such a thing? Map
, Set
or List
?
Upvotes: 1
Views: 1030
Reputation: 131326
where while adding elements that already exist with the same name (updating the number of same item) it's state (attribute stockLevel) would update accordingly to the given quantity
In your usecase, Map
is good to store the information :
Map<Product, StockLevel>
for representing a map with as key Product
and as value the number of it in stocks : StockLevel
For iterating on a Map, you could not keep the insertion order with a HashMap
but for your need, it should not be a problem.
Nevertheless, if you want to keep the insertion order when you iterate on it or that you want that the map be ordered according to some needs (alphabetical or other), you can use more sophisticated map such as TreeMap
or LinkedHashMap
Upvotes: 0
Reputation: 180
Set do not allow duplicate values, but this is not a solution. If you insert a duplicate value it will be ignored. You can choose a List of Items and then loop to find duplicates. An if condition can be added to increment it's state.
Upvotes: 0
Reputation: 38424
That would a multiset (a.k.a. a bag). You can easily roll your own implementation as a Map<Item, Integer>
, or use one of the existing classes, e.g. Google Guava's Multiset
. Apache Commons Collections also have one, so do Eclipse Collections etc.
Upvotes: 4