How to add element into ArrayList in HashMap
HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();
public synchronized void addToList(String mapKey, Item myItem) {
List<Item> itemsList = items.get(mapKey);
// if list does not exist create it
if(itemsList == null) {
itemsList = new ArrayList<Item>();
itemsList.add(myItem);
items.put(mapKey, itemsList);
} else {
// add if item is not already in list
if(!itemsList.contains(myItem)) itemsList.add(myItem);
}
}
First you have to add an ArrayList to the Map
ArrayList<Item> al = new ArrayList<Item>();
Items.add("theKey", al);
then you can add an item to the ArrayLIst that is inside the Map like this:
Items.get("theKey").add(item); // item is an object of type Item
I know, this is an old question. But just for the sake of completeness, the lambda version.
Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);