You need to create a relationship between a key and a value. In this case, you need to map products to their respective quantities.
Who does this in Java is the interface Map
. Its simplest implementation is the class HashMap
. In this type of Collections, keys are unique and cannot be repeated.
The type of data representing the quantity is simple: it can be a Integer
. The product will depend on how you want to represent it. It would be with a numerical product id (ie another Integer
)? Or maybe a tag, which could be a String
?
It would look like this then:
Map<Integer, Integer> produtosParaQuantidades = new HashMap<>();
or else:
Map<String, Integer> produtosParaQuantidades = new HashMap<>();
Then you can add and recover quantities like this:
int idDoSabãoEmPó = 5;
produtosParaQuantidades.put(idDoSabãoEmPó, 100);
int quantidadeDeSabãoEmPó = produtosParaQuantidades.get(idDoSabãoEmPó);
We need you to exemplify a scenario to better propose you the possibilities of working with Collections. For example, if you use ordered, unordered collections, those that don’t support duplicate items, etc.
– Ismael
I edited by adding more information.
– Wilker