How to Store HashMap<String, ArrayList> Inside a List
Last updated: November 6, 2023
1. Overview
In this tutorial, we’re going to discuss how to store a HashMap inside a List in Java. First, we’ll have a short explanation of HashMap and List data structures in Java. Then, we’ll write a simple code to solve the problem.
2. HashMap and List in Java
Java provides us with different data structures with various properties and characteristics to store objects. Among those, HashMap is a collection of key-value pairs that maps a unique key to a value. Also, a List holds a sequence of objects of the same type.
We can put either simple values or complex objects in these data structures.
3. Store HashMap<String, ArrayList<String>> Inside a List
Let’s have a simple example in which we create a List of HashMaps. For each book category, there is a HashMap that maps the name of a book to its authors.
First, we define javaBookAuthorsMap, which maps the name of a Java-related book to its list of authors:
HashMap<String, List<String>> javaBooksAuthorsMap = new HashMap<>();
Also, we define phpBooksAuthorsMap to hold the name and authors of a book for the PHP category:
HashMap<String, List<String>> phpBooksAuthorsMap = new HashMap<>();
Then, we define booksAuthorsMapsList to hold HashMaps for different categories:
List<HashMap<String, List<String>>> booksAuthorsMapsList = new ArrayList<>();
Now, we have a List containing two HashMaps.
To test it, we can put some books information in javaBookAuthorsMap and phpBooksAuthorsMap lists. Then, we add them to the booksAuthorsMapsList. Finally, we make sure that the HashMaps are added to the List.
Let’s see the unit test below:
@Test
public void givenMaps_whenAddToList_thenListContainsMaps() {
HashMap<String, List<String>> javaBooksAuthorsMap = new HashMap<>();
HashMap<String, List<String>> phpBooksAuthorsMap = new HashMap<>();
javaBooksAuthorsMap.put("Head First Java", Arrays.asList("Kathy Sierra", "Bert Bates"));
javaBooksAuthorsMap.put("Effective Java", Arrays.asList("Joshua Bloch"));
javaBooksAuthorsMap.put("OCA Java SE 8",
Arrays.asList("Kathy Sierra", "Bert Bates", "Elisabeth Robson"));
phpBooksAuthorsMap.put("The Joy of PHP", Arrays.asList("Alan Forbes"));
phpBooksAuthorsMap.put("Head First PHP & MySQL",
Arrays.asList("Lynn Beighley", "Michael Morrison"));
booksAuthorsMapsList.add(javaBooksAuthorsMap);
booksAuthorsMapsList.add(phpBooksAuthorsMap);
assertTrue(booksAuthorsMapsList.get(0).keySet()
.containsAll(javaBooksAuthorsMap.keySet().stream().collect(Collectors.toList())));
assertTrue(booksAuthorsMapsList.get(1).keySet()
.containsAll(phpBooksAuthorsMap.keySet().stream().collect(Collectors.toList())));
}
4. Conclusion
In this article, we talked about storing HashMaps inside a List in Java. Then, we wrote a simple example in which we added HashMap<String, ArrayList<String>> to a List<String> for Two book categories.
The examples are available over on GitHub.