Trying to add a collection of items into a hashmap of type String. I iterate over the collection and if the value isn't in the hashmap I add it to the map and if it is I increment the quantity by 1 instead of adding it again. Here is my code so far.
HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();
Collection items1 = basket.getItems();
for (Iterator i = items1.iterator(); i.hasNext(); ) {
Product p = (Product) i.next();
if(map.containsKey(p.title)) {;
}
else {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(p.price);
list.add(1);
map.put(p.title,list);
}
}
How would I access the stored integer in the ArrayList inside the HashMap and increment it by 1?
Any help would be greatly appreciated, thank you.
If I was trying to also then print that map in a table, how would I iterate through the map and print the correct values. So far I have this code:
for (Map.Entry<String, String> entry : map.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
ArrayList<Integer> l = map.get(p.title);
%>
<tr>
<td> <%out.println(map.getKey);%></td>
<td> <%out.println(l.get(0);%></td>
<td> <%out.println(l.get(1));%></td>
</tr>
<%
}
%>
I have managed to get it to work when printing the collection but not with the map.