How to add element into ArrayList in HashMap?
HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>();
In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap. This set can be passed into the ArrayList while initialization in order to obtain an ArrayList containing all the keys.
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime.
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);
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With