In Java, a HashMap is a class that implements the Map interface, it stores key-value pairs in a hash table, which allows for fast lookups, insertions, and deletions. There are several ways to update the key in a HashMap.
Here, we will explore the following:
- By removing and adding the new key/value pair with the updated key
- Using for-loop
- Using Java 8 Streams
- Using the forEach method
Update the key in a HashMap by removing and adding the new key/value pair with the updated key
Let’s create one HashMap, populate it with some key/value pairs, and replace one of the keys.
public class Test { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); map.put("four", 4); // modify the key "two" map.remove("two"); map.put("twoUpdated", 2); System.out.println(map); } }
Update the key in a HashMap using Java for-loop
We can iterate over a HashMap and populate a new one with modified keys.
public class Test { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); map.put("four", 4); // create a new HashMap Map<String, Integer> updatedMap = new HashMap<>(); // iterate over original map and put the key/values pair into a new one with modified key "two" for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getKey().equals("two")) { updatedMap.put("twoUpdatedKey", entry.getValue()); } else { updatedMap.put(entry.getKey(), entry.getValue()); } } System.out.println(updatedMap); } }
Update the key in a HashMap using Java 8 Streams
If we need to update all the keys, we can use the Streams API to create a new HashMap of the existing one, and during that process, we can change the keys.
import java.util.*; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); map.put("four", 4); // converting all keys to uppercase map = map.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey().toUpperCase(), Map.Entry::getValue)); System.out.println(map); } }
Change the key in a HashMap using the forEach method
We can also use Java 8 forEach method to change the keys in a HashMap. We will also create a new one and populate it with updated key/value pairs from the original one.
public class Test { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); map.put("four", 4); // create a new HashMap Map<String, Integer> updatedMap = new HashMap<>(); // convert the keys to uppercase and put into a new map with corresponding values map.forEach((key, value) -> updatedMap.put(key.toUpperCase(), value)); System.out.println(updatedMap); } }
Happy coding!