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 Java, the HashMap is a widely used data structure that stores elements in key-value pairs, providing fast access and retrieval of data. Sometimes, when working with HashMaps, we may want to modify the key of an existing entry.

In this tutorial, we’ll explore how to modify a key in a HashMap in Java.

2. Using remove() Then put()

First, let’s look at how HashMap stores key-value pairs. HashMap uses the Node type to maintain key-value pairs internally:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
   ...
  }

As we can see, the key declaration has the final keyword. Therefore, we cannot reassign a key object after we put it into a HashMap.

Although we cannot simply replace a key, we can still achieve our expected result in other ways. Next, Let’s look at our problem from a different angle.

Let’s say we have an entry K1 -> in a HashMap. Now, we want to change K1 into K2 to have K2 -> V. Indeed, the most straightforward idea to achieve that is finding the entry by “K1” and replacing the key “K1” with “K2”. However, we can also remove the K1 -> V association and add a new K2 -> V entry.

The Map interface offers the remove(key) method to remove an entry from the map by its key. Further, the remove() method returns the value removed from the map.

Next, let’s see how this approach works through an example. For simplicity, we’ll use unit test assertions to verify if the result is as we expect:

Map<String, Integer> playerMap = new HashMap<>();

playerMap.put("Kai", 42);
playerMap.put("Amanda", 88);
playerMap.put("Tom", 200);

The simple code above shows a HashMap, which holds a few associations of player names (String) and their scores (Integer). Next, let’s replace the player name “Kai” in the entry “Kai” -> 42 with “Eric“:

// replace Kai with Eric
playerMap.put("Eric", playerMap.remove("Kai"));

assertFalse(playerMap.containsKey("Kai"));
assertTrue(playerMap.containsKey("Eric"));
assertEquals(42, playerMap.get("Eric"));

As we can see, the single-line statement playerMap.put(“Eric”, playerMap.remove(“Kai”)); does two things. It removes the entry with the key “Kai“, takes its value (42), and adds a new entry “Eric” -> 42.

When we run the test, it passes. So, this approach works as expected.

Although our problem is solved, there is a potential question. We know that the HashMap‘s key is a final variable. So, we cannot reassign the variable. But we can modify a final object’s value. Well, in our playerMap example, the key is String. We cannot change its value as Strings are immutable. But can we solve the problem by modifying the key if it’s a mutable object?

Next, let’s figure it out.

3. Never Modify Keys in a HashMap

First, we shouldn’t use a mutable object as the key in a HashMap in Java, which can lead to potential issues and unexpected behavior.

This is because the key object in a HashMap is used to compute a hash code that determines the bucket where the corresponding value will be stored. If the key is mutable and changed after being used as a key in the HashMap, the hash code can also change. As a result, we won’t retrieve the value associated with the key correctly since it will be located in the wrong bucket.

Next, let’s understand it through an example.

First, we create a Player class with only one single property:

class Player {
    private String name;
    public Player(String name) {
        this.name = name;
    }
    
    // getter and setter methods are omitted
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Player)) {
            return false;
        }
        Player player = (Player) o;
        return name.equals(player.name);
    }
    
    @Override
    public int hashCode() {
        return name.hashCode();
    }
}

As we can see, the Player class has a setter on the name property. So, it’s mutable. Further, the hashCode() method calculates the hash code using the name property. This means changing the name of a Player object can make it have a different hash code.

Next, let’s create a map and put some entries in it, using Player objects as keys:

Map<Player, Integer> myMap = new HashMap<>();
Player kai = new Player("Kai");
Player tom = new Player("Tom");
Player amanda = new Player("Amanda");
myMap.put(kai, 42);
myMap.put(amanda, 88);
myMap.put(tom, 200);
assertTrue(myMap.containsKey(kai));

Next, let’s change the player kai‘s name from “Kai” to “Eric”, then verify if we can get the expected result:

//change Kai's name to Eric
kai.setName("Eric");
assertEquals("Eric", kai.getName());
Player eric = new Player("Eric");
assertEquals(eric, kai);

// now, the map contains neither Kai nor Eric:
assertFalse(myMap.containsKey(kai));
assertFalse(myMap.containsKey(eric));

As the test above shows, after changing kai‘s name to “Eric“, we cannot retrieve the entry “Eric” -> 42 anymore using kai or eric. However, the object Player(“Eric”) exists in the map as a key:

// although the Player("Eric") exists:
long ericCount = myMap.keySet()
  .stream()
  .filter(player -> player.getName()
    .equals("Eric"))
  .count();
assertEquals(1, ericCount);

To understand why this happened, we first need to understand how HashMap works.

HashMap maintains an internal hashtable to store the hash codes of the keys when they are added to the map. A hash code references a map entry. As we retrieve an entry, for example, by using the get(key) method, HashMap computes the hash code of the given key object and looks up the hash code in the hashtable.

In the example above, we put kai(“Kai”) in the map. So, the hash code is computed based on the string “Kai”. HashMap stored the result, let’s say “hash-kai”,  in the hashtable. Later, we changed the kai(“Kai”) to kai(“Eric”). When we tried to retrieve the entry by kai(“Eric”), HashMap computed “hash-eric” as the hash code. Then, it looked it up in the hashtable. Of course, it won’t find it.

It isn’t hard to imagine that if we did this in a real application, the root cause of this unexpected behavior can be hard to find.

Therefore, we shouldn’t use mutable objects as keys in a HashMap. Further, we should never modify the keys.

4. Conclusion

In this article, we’ve learned the “remove() then put()” approach to replacing a key in a HashMap. Further, we discussed through an example why we should avoid using mutable objects as keys in a HashMap and why we should never modify keys in a HashMap.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
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)