How to combine two Map in Java? Example Tutorial

You can combine two maps in Java by using the putAll() method of java.util.Map interface. This method copies all the mappings from one Map to another, like, if you call it like first.putAll(second), then all mappings from the second Map will be copied into the first Map. Which means if the first map contains 5 elements and the second map contains 10 elements or mapping, then the combined map will contain 15 or fewer mappings. In the case of duplicate keys, the value is overridden or updated from the second map. For example, if the first map has a mapping 1 -> One and second map has mapping 1 -> ONE then after combining the second map into the first one, the value of 1 will be ONE, i.e. the value from the second map.

The putAll() method copies all of the mappings from the specified map to this map. The effect of this call is similar to iterating over the map and calling put(k, v) on this Map once for each mapping from key k to value v in the specified map.

Btw, this is an optional operation for any Map implementation, but HashMap implements this method. You will get the UnsupportedOperationException if the putAll operation is not supported by this map.

The putAll() method also throws NullPointerException if the specified map is null, or if this map does not permit null keys or values, and the specified map contains null keys or values.

It can also throw ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map. Also, the behavior of this operation is undefined if the specified map is modified while the operation is in progress.

Now that we know enough about how to combine two Map in Java or copy values from one Map to another let's see a working example to fully understand the concept and learn how to use its code. Btw, if you are just starting with Java and need more information on Map class, then you should also see The Complete Java Masterclass course on Udemy. One of the most up-to-date course to learn Java




Java Program to Copy Values from One Map to Other

Here is a simple program to copy values from one map to other in Java. This way, you can combine mappings, like both keys and values. For example, if you receive two maps of orders from different systems, you can combine them to calculate the total notional value.

In our case, we just have two maps where numbers are mapped to their String values. In one map we have mapped number to equivalent string written in a small case and other maps we have done the same thing, but strings are in capital order.

This has been done to show that in the case of duplicate keys, the values are updated from the second map. This is the basic property of Map (see Java Fundamentals: Collections) and all the Map implementations like HashMap, ConcurrentHashMap, and Hashtable follows it.

How to combine two Map in Java? Example Tutorial


Java program to combine two maps in Java


import java.util.HashMap;
import java.util.Map;
 
public class Helloworld {
 
  public static void main(String[] args) {
 
    // first map integer to string
    Map<Integer, String> intToString = new HashMap<Integer, String>();
    intToString.put(1, "One");
    intToString.put(2, "Two");
    intToString.put(3, "Three");
    intToString.put(4, "Four");
    intToString.put(5, "Five");
 
    System.out.println("first map: " + intToString);
 
    // second map - prime numbers
    Map<Integer, String> primes = new HashMap<>();
    primes.put(2, "TWO");
    primes.put(3, "THREE");
    primes.put(5, "FIVE");
    primes.put(7, "SEVEN");
    primes.put(11, "ELEVEN");
 
    System.out.println("second map: " + primes);
 
    // when you combine map, it would contains mapping
    // from the two maps, but for duplicate keys
    // values will be updated from the second map
    // you can choose any map to source and destination
    // for example, in below code, intToString map
    // will contain combined value but primes will
    // not be changed.
 
    intToString.putAll(primes);
 
    System.out.println("combined map: " + intToString);
  }
 
}
 
Output :
first map: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
second map: {2=TWO, 3=THREE, 5=FIVE, 7=SEVEN, 11=ELEVEN}
combined map: {1=One, 2=TWO, 3=THREE, 4=Four, 5=FIVE, 7=SEVEN, 11=ELEVEN}

You can see from the output that in the combined map the value of 2, 3, and 5 is now capital TWO, THREE, and FIVE. Which means their values are updated from the second map. The combined Map also contains new mappings from the second map, like 7 and 11.

That's all about how to combine two maps in Java. It's actually very easy, you just need to remember about putAll() method of java.util.Map class. Though be careful, as I said, if your map, in which you are copying mappings has duplicate keys, then their values will be overwritten by values form the second map.

The putAll() is also an optional operation which means you cannot rely on every single map supporting this operation, but for most purpose, unless you are using HashMap or other Map implementation from JDK, it doesn't matter.

Further Learning
The Complete Java Masterclass
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java


Other Java Map tutorials you may like to explore
  • How to remove mappings from a Map? (tutorial)
  • My favorite free courses to learn Data Structure and Algorithms (courses)
  • The difference between Hashtable and HashMap in Java? (answer)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • What is the best way to iterate over a Map? (tutorial)
  • How do you find if a Map contains a key? (tutorial)
  • 5 Courses to learn Java Programming for beginners (courses)
  • What is the difference between HashMap, TreeMap, and LinkedHashMap in Java? (answer)
  • How to remove a key-value pair from HashMap in Java? (tutorial)
  • My favorite free courses to learn Java in-depth (courses)
  • How to sort a HashMap by keys in Java 8? (tutorial)
  • How to sort a Map by keys and values in Java? (tutorial)
  • The difference between HashMap and LinkedHashMap in Java? (answer)

If you like this article, then please share it with your friends and colleagues. If you have any question or doubt then, please drop a comment.

No comments:

Post a Comment