'Java, How to add values to Array List used as value in HashMap
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?
Solution 1:[1]
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!
Solution 2:[2]
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.....
Solution 3:[3]
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);
Solution 4:[4]
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)
Solution 5:[5]
Java 8+ has computeIfAbsent
examList.computeIfAbsent(map.get(id), k -> new ArrayList<>());
map.get(id).add(value);
Solution 6:[6]
Can also do this in Kotlin without using any external libraries.
var hashMap : HashMap<String, MutableList<String>> = HashMap()
if(hashMap.get(id) == null){
hashMap.put(id, mutableListOf<String>("yourString"))
} else{
hashMap.get(id)?.add("yourString")
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mechkov |
| Solution 2 | Chetan |
| Solution 3 | Óscar López |
| Solution 4 | Matt Fenwick |
| Solution 5 | Diacrome |
| Solution 6 |
