Reputation: 4163
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
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:
baz
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
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
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
Reputation: 3141
You should defined new ArrayList object and put it with key
Upvotes: 0