java-Ways to create and initialize java HashMap inline

1. The purpose of this post

I would demo how to create and initialize java HashMap inline by different methods.

2. Environments

  • java 1.8+
  • Vavr 0.9+
  • Guava 25.0+

3. Ways to create and initialize java HashMap inline

3.1 For jdk versions less or equal to java 8

3.1.1 The imperative way

The most imperative way to create a java HashMap is:

    public static Map initialMapByJava8_1() {
        Map<String,String> map = new java.util.HashMap<>();
        map.put("key1","value1");
        map.put("key2","value2");
        return map;
    }

3.1.2 The anonymous class

Use Anonymous Subclass to Initialize a HashMap This creates an anonymous subclass of HashMap, whose instance initializer puts these values. In other words it creates a new class that inherits from HashMap. This is the shortest way to create and initialize a dynamic HashMap

    return new java.util.HashMap<String,String>() {
        {
            put("key1","value1");
            put("key2","value2");
        }
    };

3.2 For Java Version 9 or higher

3.2.1 Use Map.of to create immutable map inline

    private static Map initialMapByJava9() {
        return Map.of("1", "A", "2", "B", "3", "C");
    }

the Map.of method is defined for up to ten elements in the map, while the Map.ofEntries method will have no such limit.

The return type is unmodifiable, if you want to make it modifiable.

new HashMap(Map.of(...));

3.2.2 Use Map.ofEntries to create immutable map inline

    private static Map initialMapByJava9_2() {
        return Map.ofEntries(Map.entry("a","1"),Map.entry("b","2"));
    }

The return type is unmodifiable, if you want to make it modifiable.

new HashMap(Map.ofEntries(...));

3.3 Use library: Vavr

According to the Vavr’s website:

Vavr is an object-functional language extension to Java 8, which aims to reduce the lines of code and increase code quality. It provides persistent collections, functional abstractions for error handling, concurrent programming, pattern matching and much more.

Because Vavr does not depend on any libraries (other than the JVM) you can easily add it as standalone .jar to your classpath.

First, add the vavr dependency to your pom:

    <dependency>
        <groupId>io.vavr</groupId>
        <artifactId>vavr</artifactId>
        <version>0.10.0</version>
    </dependency>

Then ,use the Guava’s HashMap to create and initialize the Map:

import io.vavr.collection.HashMap;
....
    private static Map initialMapByVavr() {
        return HashMap.of("key1", "val1", "key2", "val2", "key3", "val3").toJavaMap();
    }

The toJavaMap would return a modifiable HashMap.

3.4 Use library: Guava

Guava is a set of core libraries that includes new collection types (such as multimap and multiset), immutable collections, a graph library, functional types, an in-memory cache, and APIs/utilities for concurrency, I/O, hashing, primitives, reflection, string processing, and much more!

First,add Guava to your pom:

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>25.0-jre</version>
        </dependency>

Then, use the Guava’s ImmutableMap.of to create and initialize the Map:

import com.google.common.collect.ImmutableMap;
...
    private static Map initialMapByGuava() {
        return ImmutableMap.of("a", 1, "b", 2, "c", 3);
    }

4. Summary

Create and initialize a java HashMap is easy by using libraries,but you can still just use the jdk way to do this job.