Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, How to add values to Array List used as value in HashMap

Tags:

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?

like image 654
vedran Avatar asked Nov 01 '11 16:11

vedran


People also ask

Can we store array as value in HashMap?

In a HashMap, keys and values can be added using the HashMap. put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.


2 Answers

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 this:

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. 
like image 137
dunni Avatar answered Oct 03 '22 06:10

dunni


String courseID = "Comp-101"; List<String> scores = new ArrayList<String> (); scores.add("100"); scores.add("90"); scores.add("80"); scores.add("97");  Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>(); myMap.put(courseID, scores); 

Hope this helps!

like image 31
Mechkov Avatar answered Oct 03 '22 08:10

Mechkov