How to join two HashMaps in Java

  • Post last modified:April 16, 2023
  • Reading time:4 mins read

Discussing 4 options to join hashmaps in Java

Introduction

  • Joining two or more maps is a very common operation while developing in Java. There are many use cases where we need to join the map.
  • In this article, we will learn different options to join two maps in Java.

Use Case

  • Let’s say we have a default server configuration in the map. 
  • Each environment will have some of its own configurations. Now we can merge the dev config & prod config with the default config.
  • The below code sets up the default_config, dev_config, and prod_config.
public static void main(String[] args) {
        Map<String, String> default_config = default_config();
        Map<String, String> dev_config = dev_config();
        Map<String, String> prod_config = prod_config();
 }

  public static Map<String, String> default_config() {
        Map<String, String> default_config = new HashMap<>();
        default_config.put("prop_1", "val_1");
        default_config.put("prop_2", "val_2");
        default_config.put("prop_3", "val_3");
        default_config.put("prop_4", "val_4");
        default_config.put("prop_5", "val_5");
        return default_config;
    }

    public static Map<String, String> dev_config(){
        Map<String, String> dev_config = new HashMap<>();
        dev_config.put("prop_1", "dev_val_1");
        dev_config.put("prop_2", "dev_val_2");
        dev_config.put("prop_3", "dev_val_3");
        dev_config.put("prop_4", "dev_val_4");
        return dev_config;
    }

    public static Map<String, String> prod_config(){
        Map<String, String> prod_config = new HashMap<>();
        prod_config.put("prop_1", "prod_val_1");
        prod_config.put("prop_2", "prod_val_2");
        prod_config.put("prop_3", "prod_val_3");
        prod_config.put("prop_4", "prod_val_4");
        return prod_config;
    }

Option1

  • In this option, we iterate over each dev config and check if the key exists in the default config if yes then we override it with the dev config and return updated the default config as dev config.
public static void option_1(Map<String, String> default_config, final Map<String, String> dev_config, final Map<String, String> prod_config) {

        default_config.forEach((k, v) -> {
            if (dev_config.containsKey(k)) {
                default_config.put(k, dev_config.get(k));
            }
        });
        System.out.println(default_config);
    }

Option2

  • We can use the putAll method on hashmap to merge hashmap. It’s the most convenient way to merge the hashmap.
public static void option2(Map<String, String> default_config, Map<String, String> dev_config, Map<String, String> prod_config) {
        default_config.putAll(dev_config);
        dev_config = default_config;
        System.out.println(dev_config);

        default_config.putAll(prod_config);
        prod_config = default_config;
        System.out.println(prod_config);
    }

Option3

  • Another method is merge. where we can iterate over default_config and merge with dev_config.
  • If the default config is not present then it will get inserted in dev_config, otherwise, if the key is present then it will take the resolution logic as a function.
public static void option2(Map<String, String> default_config, Map<String, String> dev_config, Map<String, String> prod_config) {
        // dev_config = common_props + diff_with_default
        default_config.forEach((k, v) -> dev_config.merge(k, v, (v1, v2) -> v1));
        System.out.println(dev_config);
        // prod_config = common_props + diff_with_default
        default_config.forEach((k, v) -> prod_config.merge(k, v, (v1, v2) -> v1));
        System.out.println(prod_config);
    }

Option4

  • Google Guava also provides some helper methods that allow us to join hashmap.
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.1-jre</version>
        </dependency>
  • Maps.difference method will provide the difference between two hash maps. 
  • we can find the diff between dev_config and default_config using entriesOnlyOnRight method and once we have the diff we can use putAll method to merge the diff into dev_config.

public static void option3(Map<String, String> default_config, Map<String, String> dev_config, Map<String, String> prod_config){
        MapDifference<String, String> difference = Maps.difference(dev_config, default_config);
        dev_config.putAll(difference.entriesOnlyOnRight());
        System.out.println(dev_config);
    }

Conclusion

  • In this article, we discussed how to join two hashmaps. Java provides putAll, merge method to merge hashmap easily.
  • We can also use a library such as a google guava that provides helper methods to join hashmaps in Java.

Do you know another approach? Please share it in the comments.

Before You Leave

  • Let me know if I can be of any help to your career, I would love to chat or jump on a call. you can connect me over Linkedin.
  • If you like this content consider supporting it.
  • If you want to upskill your Java skills, you should definitely check out
    Java Programming Masterclass updated to Java 17
    [ 750,000 students already enrolled, with 4.5 stars]

Leave a Reply