How to Add Values to an ArrayList Used as a Value in a HashMap in Java
Java collections provide flexible ways to organize and group data. In some scenarios, a single key may need to be associated with multiple values rather than just one. A practical way to implement this is by using a HashMap where each key maps to an ArrayList. This pattern is useful for grouping related data, such as storing multiple orders per customer, multiple students per course, or multiple log entries per category.
In this article, we will explore multiple ways to add values to an ArrayList stored as a value in a HashMap.
1. Understanding the Data Structure
A Map<K, List<V>> allows multiple values to be associated with a single key. Instead of mapping a key to a single object, we map it to a list that can hold multiple items.
For example, a map of departments and employees might look like this:
Engineering -> [Thomas, James] HR -> [Carol] Marketing -> [Dave, Emma]
In Java, this structure is typically declared like this:
Map<String, List<String>> map = new HashMap<>(); Map<String, List<String>> departmentEmployees = new HashMap<>();
Here, the key represents the department name, while the value is a list containing employee names. The challenge is ensuring that the list exists before adding values to it.
2. Adding Values Using the Traditional Approach
One solution is to check whether the key already exists in the map before adding a value. If the key does not exist, a new ArrayList is created and inserted into the map. This method works with all Java versions.
public class JavaHashmapArraylistExample {
public static void main(String[] args) {
Map<String, List<String>> departmentEmployees = new HashMap<>();
addEmployee(departmentEmployees, "Engineering", "Thomas");
addEmployee(departmentEmployees, "Engineering", "James");
addEmployee(departmentEmployees, "Marketing", "Emma");
addEmployee(departmentEmployees, "Marketing", "Dave");
addEmployee(departmentEmployees, "HR", "Carol");
System.out.println(departmentEmployees);
}
public static void addEmployee(Map<String, List<String>> map, String department, String employee) {
if (!map.containsKey(department)) {
map.put(department, new ArrayList<>());
}
map.get(department).add(employee);
}
}
In this example, the addEmployee method checks whether the department already exists in the map using containsKey(). If the key is not present, a new ArrayList is created and added to the map using put(). Once the list exists, the method retrieves it using get() and adds the employee name. Although this method works well, it involves multiple steps and can lead to repetitive code in larger applications.
Output
{Engineering=[Thomas, James], HR=[Carol], Marketing=[Emma, Dave]}
3. Adding Values Using computeIfAbsent()
Java 8 introduced the computeIfAbsent() method, which provides a cleaner and more concise solution for this pattern. Instead of manually checking whether a key exists, this method automatically creates the value if the key is missing. This approach reduces boilerplate code and improves readability.
public class ComputeIfAbsentExample {
public static void main(String[] args) {
Map<String, List<String>> departmentEmployees = new HashMap<>();
addEmployee(departmentEmployees, "Engineering", "Thomas");
addEmployee(departmentEmployees, "Engineering", "James");
addEmployee(departmentEmployees, "Marketing", "Emma");
addEmployee(departmentEmployees, "Marketing", "Dave");
addEmployee(departmentEmployees, "HR", "Carol");
System.out.println(departmentEmployees);
}
public static void addEmployee(Map<String, List<String>> map, String department, String employee) {
map.computeIfAbsent(department, key -> new ArrayList<>())
.add(employee);
}
}
In this implementation, computeIfAbsent() checks whether a list already exists for the specified department. If it does not, Java automatically creates a new ArrayList. The method then returns the list, allowing the add() method to be called immediately. This makes the code more concise and eliminates the need for explicit conditional checks.
4. Using Spring’s MultiValueMap
If we are working within a Spring-based application, we can use the MultiValueMap interface. This interface is designed specifically for scenarios where a key needs to be associated with multiple values. It eliminates the need to manually create or manage lists.
Spring provides an implementation called LinkedMultiValueMap that automatically manages the collection of values for each key.
public class SpringMultiValueMapExample {
public static void main(String[] args) {
MultiValueMap<String, String> departmentEmployees = new LinkedMultiValueMap<>();
departmentEmployees.add("Engineering", "Thomas");
departmentEmployees.add("Engineering", "James");
departmentEmployees.add("Marketing", "Emma");
departmentEmployees.add("Marketing", "Dave");
departmentEmployees.add("HR", "Carol");
System.out.println(departmentEmployees);
}
}
In this example, LinkedMultiValueMap automatically creates and manages the lists associated with each key. The add() method appends values to the list corresponding to the given key. If the key does not already exist, the list is created automatically. This approach simplifies the code significantly, especially in applications that already depend on Spring.
To use MultiValueMap, the Spring Core dependency must be included in your project.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>7.0.5</version>
</dependency>
This dependency provides the MultiValueMap interface and the LinkedMultiValueMap implementation used in the example.
5. Using MultiValuedMap from Apache Commons Collections
Another option is the MultiValuedMap interface from Apache Commons Collections. This library provides specialised collection types designed for handling multiple values per key.
A commonly used implementation is ArrayListValuedHashMap, which internally stores values in ArrayList instances.
public class ApacheMultiValuedMapExample {
public static void main(String[] args) {
MultiValuedMap<String, String> departmentEmployees = new ArrayListValuedHashMap<>();
departmentEmployees.put("Engineering", "Thomas");
departmentEmployees.put("Engineering", "James");
departmentEmployees.put("Marketing", "Emma");
departmentEmployees.put("Marketing", "Dave");
departmentEmployees.put("HR", "Carol");
System.out.println(departmentEmployees);
}
}
In this implementation, ArrayListValuedHashMap automatically manages the list of values for each key. Each call to put() adds a value to the collection associated with the specified key. If the key does not exist, the library automatically creates the underlying list. This removes the need for conditional checks and manual list initialization.
To use this functionality, we need to add the Apache Commons Collections dependency to our project.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.5.0</version>
</dependency>
6. Conclusion
Associating multiple values with a single key is a common requirement in many Java applications. While a HashMap combined with ArrayList provides a straightforward solution, managing the lists manually can lead to repetitive code.
The traditional approach using containsKey() works in any Java version, but modern Java provides a cleaner solution through computeIfAbsent(). Additionally, libraries such as Spring and Apache Commons Collections offer specialized data structures like MultiValueMap and MultiValuedMap that simplify multi-value mappings even further.
7. Download the Source Code
This article explored how to add items to an ArrayList stored as values in a HashMap in Java.
You can download the full source code of this example here: Java Hashmap add items ArrayList values

