Java 9 Map.ofEntries() Method - Create Immutable Map Example

With Java 9, new factory methods are added to List, Set and Map interfaces to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in a concise way.
In this post, I show you how to create an immutable Map using Java 9 provided Map.ofEntries() static factory method.

Create Immutable Map

Map factory methods are the same as List or Set overloaded factory methods. The only difference is that the signatures of the methods take alternating keys and values as arguments. e.g.
static <K,V> Map<K,V>   of()
static <K,V> Map<K,V>   of(K k1, V v1)
static <K,V> Map<K,V>   of(K k1, V v1, K k2, V v2)
static <K,V> Map<K,V>   ofEntries(Map.Entry<? extends K,? extends V>... entries)

Create Immutable Map Before Java 9 Example

Prior to Java 9, the creation of an immutable Map was some kind of verbose task. For Example:
public class ImmutableMapExample {

    public static void main(String[] args) {

        // Creating a HashMap
        Map < String, Integer > numberMapping = new HashMap < > ();

        // Adding key-value pairs to a HashMap
        numberMapping.put("One", 1);
        numberMapping.put("Two", 2);
        numberMapping.put("Three", 3);

{One=1, Two=2, Three=3}

Create Immutable Map Example - Java 9 Map.ofEntries() Method

Let’s take an example of creating an immutable Map in java 9.
package net.javaguides.corejava.java9;

import java.util.Map;

public class ImmutableMapExample {

    public static void main(String[] args) {
        Map < String, String > fruits = Map.ofEntries(
            Map.entry("1", "Banana"),
            Map.entry("2", "Apple"),
            Map.entry("3", "Mango"),
            Map.entry("4", "Orange"));


{1=Banana, 2=Apple, 3=Mango, 4=Orange}

Related Java 9 Posts

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course