Take the 2-minute tour ×

What I have is a HashMap<String, ArrayList<String>> called examList. What I want to use it for is to save grades of each course a person is attending. So key for this HashMap is couresID, and value is a ArrayList of all grades (exam attempts) this person has made.

The problem is I know how to work with array lists and hashmaps normally, but I'm not sure how to even begin with this example. So how would I, or example, add something to ArrayList inside HashMap?

share|improve this question

4 Answers 4

up vote 11 down vote accepted

You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).

However, if you don't want to use an external lib, then you would do something like that:

if (map.get(id) == null) { //gets the value for an id)
    map.put(id, new ArrayList<String>); //no ArrayList assigned, create new ArrayList

map.get(id).add(value); //adds value to list.
share|improve this answer
There's also Spring MultiValueMap and LinkedMultiValueMap –  eduardohl Feb 19 at 16:58
String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();

Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);

Hope this helps!

share|improve this answer
and how can i get the keys,values? –  David Oct 21 '13 at 12:41
@David Use the HashMap's keySet() method. It will return all keys which in the above example would be Strings. Then for each key, you can get the corresponding ArrayList<String> by using the HashMap's get(key) method, where 'key' is the keys you retrieved earlier. Hope this helps! –  Mechkov Oct 21 '13 at 12:43
thank you man!very usefull! –  David Oct 21 '13 at 12:44
@David no problem. –  Mechkov Oct 21 '13 at 12:44

First you retreieve the value (given a key) and then you add a new element to it

    ArrayList<String> grades = examList.get(courseId);
share|improve this answer

First, you have to lookup the correct ArrayList in the HashMap:

ArrayList<String> myAList = theHashMap.get(courseID)

Then, add the new grade to the ArrayList:

share|improve this answer

Your Answer


