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
?
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With