Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add element into ArrayList in HashMap

How to add element into ArrayList in HashMap?

    HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>(); 
like image 377
lunar Avatar asked Aug 26 '12 23:08

lunar


People also ask

Can we add HashMap to ArrayList?

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.

Can we add List in HashMap?

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.

Can we add element to ArrayList in Java?

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.


2 Answers

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); 
like image 94
pan Avatar answered Oct 18 '22 14:10

pan


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);     } } 
like image 38
Tobias N. Sasse Avatar answered Oct 18 '22 12:10

Tobias N. Sasse