eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll explore using a Map in Java to store several values for a single key. One way to do this is to use a List as the Map value type and add the elements there, with a data structure of the form Map<K, List<V>>.

We’ll demonstrate using a HashMap and ArrayList, though you can use any other Map and List implementations instead. Alternatively, we can use external libraries that support data structures with multiple values. We’ll cover three ways to implement this approach, including how to safely add multiple values to the same key.

2. Manual Handling of Keys, Values, and List Elements

With this first approach, we’ll handle everything ourselves and add the keys manually:

public static Map<String, List> addKeyManually(Map<String, List> map, String key, String value) {
    if (!map.containsKey(key)) {
        map.put(key, new ArrayList());
    }
    map.get(key).add(value);
    return map;
}

We’re manually checking if the HashMap contains the key that we’re trying to add to ensure there’s a valid ArrayList to store our values. If the key doesn’t contain a valid List, we will assign one to the dictionary with the put method, having map.put(key, new ArrayList<>()).

Once we know there is a valid List in our map for the given key, we can add values manually to the List. We can retrieve this List with the get method as map.get(key). Then, with the List we can use the add method to add the value, ending up with map.get(key).add(value).

We can directly use this method on an empty HashMap:

Map<String, List<String>> map = new HashMap<>();
ArrayListInHashMap.addKeyManually(map, K1, K1_V1);
ArrayListInHashMap.addKeyManually(map, K1, K1_V2);
ArrayListInHashMap.addKeyManually(map, K2, K2_V1);

This will construct a map that looks like {key1=[key1_value1, key1_value2], key2=[key2_value1]}. We can see that not every List needs to contain the same number of values. 

This solution is a bit verbose, but it’s very generic because we can use it in any Java version (even Java 5), and it helps understand the basic logic of this implementation. 

However, this version is less computationally optimal than the following solutions. Here we’re performing two or three lookups. Two lookups are done with the containsKeyand with the get method. We can run into a third lookup if we perform the put operation. We can optimize the code with a null check to avoid the calls to both containsKey and get.

3. Leveraging the computeIfAbsent Method

Since Java 8, we can use the method computeIfAbsent of the Map interface. We can use this computeIfAbsent method to retrieve the value for a given key in a map by passing the key and, if this key is absent, a mapping to obtain a new value and insert it into the map:

public static Map<String, List> addKeyWithComputeIfAbsent(
  Map<String, List> map, String key, String value) {
    map.computeIfAbsent(key, k -> new ArrayList()).add(value);
    return map;
}

By using computeIfAbsent we don’t need to manually perform the containsKey checks, since this is automatically performed with the initialization.

Again, we can construct the same map as we constructed before:

Map<String, List<String>> map = new HashMap<>;
ArrayListInHashMap.addKeyWithComputeIfAbsent(map, K1, K1_V1);
ArrayListInHashMap.addKeyWithComputeIfAbsent(map, K1, K1_V2);
ArrayListInHashMap.addKeyWithComputeIfAbsent(map, K2, K2_V1);

The main advantage of this code is that we’re automating and optimizing operations with computeIfAbsent, which we were doing manually before. computeIfAbsent does a single lookup versus the two or three lookups from the previous version, as it searches for the key once and decides what to do while it’s already at that memory location. However, we do need a version of Java newer than Java 8 for computeIfAbsent to be available.

4. With External Libraries

Of course, storing several values for a single key in a HashMap is a problem that we often encounter. Thus, we can rely on data structures that external libraries provide to solve this problem. We’ll cover the three most popular ones so that we can use the one we’re already using in our codebase.

4.1. MultiValuedMap From Apache Commons Collections

The Apache Commons Collections library provides the MultiValuedMap interface that allows us to store several values for a single key:

public static MultiValuedMap<String, String> addKeyToApacheMultiValuedMap(
  MultiValuedMap<String, String> map, String key, String value) {
    map.put(key, value);
    return map;
}

This looks like previous approaches, but we don’t need to manage the ArrayList part manually, and we just call the put method that handles everything for us. There are many other helper methods for us to interact with the content of our map easily.

4.2. LinkedMultiValueMap From Spring

Another popular library with support for maps with several values for a single key is Spring. It provides the interface LinkedMultiValueMap to achieve our objective:

public static MultiValueMap<String, String> addKeyToSpringLinkedMultiValueMap(
  MultiValueMap<String, String> map, String key, String value) {
    map.add(key, value);
    return map;
}

We can see that the map type is declared using two strings, MultiValueMap<String, String>, since it’s a LinkedMultiValueMap that takes care of handling values with the same key. Before, we were using a HashMap that had a String for each key and a corresponding List<String> as the value.

4.3. Multimap From Google Guava

Finally, another popular library is Google’s Guava, which provides the Multimap interface to have a map with keys storing several values:

public static Multimap<String, String> addKeyToGuavaMultimap(
  Multimap<String, String> map, String key, String value) {
    map.put(key, value);
    return map;
}

We see that the syntax is very similar for all external libraries. The Guava library is very efficient, and it’s widely used in many big projects, so we may have support for our map needs straight out of the box if we’re already using it in our codebase.

5. Conclusion

In this article, we’ve talked about solutions to have several values for a single key in a map-like structure. We’ve covered three solutions that we can choose from based on our code and needs.

The first solution details every step of the process as we handle manually the values in an ArrayList assigned to each key in the HashMap. It’s a solution compatible with all Java versions, but it’s slightly verbose. Moreover, depending on our implementation, we may run into some computational overhead that newer libraries don’t require.

The second approach can be used to leverage on some newer methods. It still uses a Map with an List to store several values for each key, but we rely on some methods to automate the use of the interface and perform checks.

Finally, the third solution presented looks at interfaces implemented in external libraries, namely MultiValuedMap from Apache Commons Collections, LinkedMultiValueMap from Spring, and Multimap from Google Guava. If we’re already using any of those libraries in our codebase, we can rely on these structures to simplify our code.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments