TheRookierLearner
TheRookierLearner

Reputation: 4163

How do I add elements to an ArrayList in a map?

I create an ArrayList in a map using

Map <String, ArrayList<String>> firmMSAMap = new HashMap<String, ArrayList<String>>() ;

How do I add elements to the ArrayList within this map? Please correct me if my delcaration is wrong. I am trying to have a Map which contains an ArrayList

Upvotes: 0

Views: 919

Answers (4)

jahroy
jahroy

Reputation: 22692

Add the String foo to the ArrayList keyed by the String baz:

firmMSAMap.get("baz").add("foo");

The above code does the following:

  1. It retrieves the ArrayList stored with the key baz
  2. It adds a String to the ArrayList

NOTE: This assumes that the Map already contains a value for the ke `baz.

Otherwise you would have to create a new ArrayList like this:

firmMSAMap.put("baz", new ArrayList<String>());

Here's a better example that checks to see if a value is mapped first:

Map<String, List<String>> theMap = ...

if (theMap.containsKey("baz")) {
    theMap.get("baz").add("foo");
}
else {
    List<String> tempList = new ArrayList<String>();
    tempList.add("foo");
    theMap.put("baz", tempList);
}

Upvotes: 7

Pshemo
Pshemo

Reputation: 124225

You need to get that ArrayList from map and add element to it like

firmMSAMap.get("your List key").add("new element of list");

But of course to be able to do it your map need to contain that "your List key"->ArrayList pair first, so you need to put it there before

firmMSAMap.put("your List key", new ArrayList<String>());

Upvotes: 1

Steve H.
Steve H.

Reputation: 6947

This maps String keys to ArrayList values. So if you want an ArrayList at key "foo", then:

firmMSAMap.put("foo", new ArrayList<String>());

Upvotes: -1

Arsen Alexanyan
Arsen Alexanyan

Reputation: 3141

You should defined new ArrayList object and put it with key

Upvotes: 0

Related Questions