-3

How to add an Element to an ArrayList within a HashMap?

This is a question, that I have asked myself many times and forgot it after solving it. I guess many have the same one so here is the simple answer to it.

// Example
HashMap<String, ArrayList<String>> someElements = new HashMap<String, ArrayList<String>>();
Georgios
  • 861
  • 2
  • 12
  • 30
  • 1
    Get the value using `get`. Then add an element to the list using `add`. `map.get(key).add(entry);`. Obviously, you first need to put an actual list in there. `map.put(key, new ArrayList<>());`. – Zabuzard Feb 13 '19 at 12:54
  • Note that there is also a handy method to do both in one step: `map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);` – Zabuzard Feb 13 '19 at 12:57

1 Answers1

0
// fill the HashMap with the key that you need
// initiate it with an empty ArrayList        
   someElements.put("keyString" , new ArrayList<String>());

// Later when wanting to add an element to the ArrayList of a key use
   someElements.get("keyString").add("TheStringValue");
Georgios
  • 861
  • 2
  • 12
  • 30
  • @funkyjelly It is encouraged to ask a question at SO if it is not covered yet. So if we do not decide to close this as duplicate or for another reason, this answer is completely valid and OPs behavior is encouraged by SO rules. – Zabuzard Feb 13 '19 at 12:56
  • But even if, this only means that the question should be down-voted, not the answer. – Zabuzard Feb 13 '19 at 12:58
  • 1
    @Zabuza Agreed and didn't downvote. Deleted comment – nullPointer Feb 13 '19 at 13:09