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
?
First you retreieve the value (given a key) and then you add a new element to it
ArrayList<String> grades = examList.get(courseId);
grades.add(aGrade);
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!
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
:
myAList.add(newGrade)
Java 8+ has computeIfAbsent
examList.computeIfAbsent(map.get(id), k -> new ArrayList<>());
map.get(id).add(value);
First create HashMap.
HashMap> mapList = new HashMap>();
Get value from HashMap against your input key.
ArrayList arrayList = mapList.get(key);
Add value to arraylist.
arrayList.add(addvalue);
Then again put arraylist against that key value. mapList.put(key,arrayList);
It will work.....
Source: Stackoverflow.com