Member-only story
A way of keeping a list of values as the value in a Java HashMap (example with people to grades)
If you’re wondering how to keep a list of values type as the value in a key, value pair in a HashMap data structure in Java, then you’re in the right place.
This article will go over one way to accomplish this.
Let’s say that you have the following code:
Basically, for each person listed in the 2-D array peopleToGrades
, I want to store all of their associated grades. How can we do this?
Well, one way we can do this is to store that data in a HashMap
data structure that maps a String
(the person’s name) to a ArrayList
of String
values (the person’s grades). That code would look like this:
So basically, we declare an empty peopleToGradesMap
on line 12.
On line 14, we then loop through the length of peopleToGrades
which is given on lines 1 through 10.
On line 15, we check if the peopleToGradesMap
does not contain the name of the inner array we’re looking at.
If the map does not contain that name already, we then create a new ArrayList<String>
on line 16, and on line 17 we get that name in the map and then add the peopleToGrades[i][1]
to it, which basically means that we add the grade to the list associated with that person in the map.
If the map does contain the name already, then we skip the first block there and go straight to the else
. We just add the grade to the value, which is the list of String
values (grades) associated with that person.
All goes well during this program, and the map looks like this at the end of execution:
{Jeremy=[A-, B-], Yuta=[B], Tremaine=[A], Damian=[A]…