Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

A way of keeping a list of values as the value in a Java HashMap (example with people to grades)

Tremaine Eto
Dev Genius
Published in
2 min readMay 2, 2021

--

Photo by heylagostechie on Unsplash

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]…

--

--

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Tremaine Eto

Senior Software Engineer @ Iterable | Previously worked at DIRECTV, AT&T, and Tinder | UCLA Computer Science alumni | Follow me for software engineering tips!

No responses yet