Java HashMap merge
last modified May 31, 2025
This article demonstrates how to use the merge
method in Java's
HashMap
to combine values for duplicate keys.
The merge
method provides a powerful way to handle key-value
combinations in HashMaps. It's particularly useful when you need to:
- Combine values for existing keys
- Conditionally add new entries
- Implement custom merging logic
- Handle concurrent updates safely
This is the method signature:
V merge(K key, V value, BiFunction<V,V,V> remappingFunction)
The merge
method takes three parameters:
key
: The key for which the value should be merged.value
: The new value to be merged with the existing value.remappingFunction
: A function that defines how to combine the existing value with the new value if the key already exists.
The remappingFunction
is a BiFunction
that takes
two parameters: the existing value and the new value. It returns the
combined value that will be stored in the map. If the key does not exist,
the merge
method will add the key with the new value.
If the key exists, it will apply the remappingFunction
to
combine the existing value with the new value.
Counting words
In this example, we will use the merge
method to count the
occurrences of words in an array. The merge
method allows us to
efficiently update the count for each word as we iterate through the array.
If a word already exists in the map, we will merge its current count with the
new count using a lambda expression.
If the word does not exist, it will be added with an initial count of 1. This approach eliminates the need for explicit checks for key existence, making the code cleaner and more concise.
void main() { HashMap<String, Integer> wordCounts = new HashMap<>(); String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"}; for (String word : words) { wordCounts.merge(word, 1, (oldValue, newValue) -> oldValue + newValue); } System.out.println(wordCounts); }
This counts word occurrences by merging values when keys already exist.
Advanced Merge Scenarios
In this section, we explore more complex scenarios using the merge
method, including conditional updates and handling null values.
void main() { HashMap<String, BigDecimal> productPrices = new HashMap<>(); productPrices.put("Laptop", BigDecimal.valueOf(799.99)); productPrices.put("Phone", BigDecimal.valueOf(699.99)); // Only update if the new price is lower productPrices.merge("Laptop", BigDecimal.valueOf(599.99), (oldPrice, newPrice) -> newPrice.compareTo(oldPrice) < 0 ? newPrice : oldPrice); System.out.println(productPrices); }
This example demonstrates how to conditionally update a value based on a
comparison with the existing value. The merge
method allows you to
implement custom logic for merging values, making it versatile for various
use cases.
Null Values
The merge
method helps update values efficiently, but it does
not accept null
as a new value in the remapping function. If
null
is passed, it will cause a NullPointerException
.
void main(String[] args) { HashMap<String, Integer> scores = new HashMap<>(); // Merging existing values scores.merge("Alice", 100, (oldScore, newScore) -> oldScore + newScore); // Ensure non-null values are provided scores.merge("Bob", 0, (oldScore, newScore) -> oldScore + newScore); System.out.println(scores); }
When merging values, you should avoid passing null
as the new
value. Instead, initialize with a default value (e.g., 0
for
numbers). This ensures safe updates without unexpected exceptions.
Inventory Management
In this example, we will use the merge
method to manage an
inventory system. The merge
method allows us to efficiently
update product quantities when new shipments arrive.
record Product(String name, int quantity) { } void main() { HashMap<String, Product> inventory = new HashMap<>(); inventory.merge("A100", new Product("Laptop", 5), (oldProduct, newProduct) -> new Product(oldProduct.name, oldProduct.quantity + newProduct.quantity)); inventory.merge("A100", new Product("Laptop", 3), (oldProduct, newProduct) -> new Product(oldProduct.name, oldProduct.quantity + newProduct.quantity)); System.out.println(inventory); }
This example demonstrates how to merge product quantities in an inventory
system. The merge
method allows you to combine existing product
quantities with new shipments efficiently, ensuring that the total quantity
is updated correctly without needing to check if the key exists first.
Source
Java HashMap merge documentation
The merge
method provides a concise, thread-safe way to handle
complex HashMap
operations with clean, readable code.
Author
List all Java tutorials.