I have a shopping site, in which items can be added to a basket, each item is an instance of a class Product, and all the items are stored in a Collection<Product>
items,
I am currently then iterating through that list and displaying each item in a table.
However I want to display a quantity value for each item instead.
I created a Map
, and am trying to put each of my products into it.
However each Product is still listed as only existing once because each class instance is different?
How would I adjust this?
My Product class has a product ID value. Here's the code I have currently.
Map<Product, Integer> map = new HashMap<>();
for (Product p : items) {
Integer i = map.get(p);
if (i == null) {
map.put(p, 1);
}
else {
map.put(p, i+1);
}
}
Having implemented hashcode and equals methods.
Trying to add the items to the map.
Collection<Product> items = basket.getItems();
Map<Product, Integer> map = new HashMap<>();
for (Product p : items) {
for (Product key : map.keySet()) {
if (p.equals(key)) {
map.put(key, map.get(key));
}
else {
map.put(p, 1);
}
}
}