Java how to initialize map

How to Initialize a HashMap Inline in Java

Examples of creating and adding the key-value pairs to a Java HashMap inline.

Overview

The HashMaps are key-value-based unordered, unsorted collections. We often use HashMaps in Java and put hard-coded values in it. Today, we will cover various ways of creating and initializing Java HashMaps inline. Also, we will learn to create Immutable, Singleton, and Empty maps.

Creating a Simple HashMap

The most basic way of creating a HashMap instance and adding a few elements is to use a constructor to create an empty HashMap and then add elements one by one.
Example of initializing a simple HashMap.

Map map = new HashMap<>(); map.put("color", "black"); map.put("drink", "coffee"); map.put("shape", "slim");Code language: Java (java)

Although this is a two-step operation, the HashMap we created is mutable; thus, we can add, remove, or modify elements.

Creating a HashMap using Anonymous Subclass

We can use an anonymous subclass to instantiate and initialize a Java HashMap in the same line.

Map map = new HashMap<>() < < put("color", "black"); put("drink", "coffee"); put("shape", "slim"); > >;Code language: Java (java)

This way is not recommended for initializing a Java HashMap as it has a lot of overhead and potential memory leak issues.

Читайте также:  Python call code object

Creating an Immutable HashMap

The Java Collections class offers the unmodifiableMap() method that creates an immutable HashMap containing the elements from the given Map.
Example of initializing an immutable Java HashMap.

Map map = new HashMap<>(); map.put("color", "black"); map.put("drink", "coffee"); map.put("shape", "slim"); Map immutableMap = Collections.unmodifiableMap(map);Code language: Java (java)

Using the Collections unmodifiableMap() method, we can create an immutable copy of an existing Java HashMap. As the resulting HashMap is immutable, we cannot add, update, or remove elements.

Creating a Singleton HashMap

The singletonMap() method of the Java Collections class creates an immutable HashMap containing the given key-value pair.
Example of creating a singleton HashMap.

Map map = Collections.singletonMap("color", "black");Code language: Java (java)

A singleton HashMap contains one and only one key-value pair. As it is immutable, we cannot modify its contents.

Creating an Empty HashMap

The emptyMap() method of the Java Collections class creates an empty HashMap instance.
Example of creating an empty Java HashMap.

Map map = Collections.emptyMap();Code language: Java (java)

Please note that the resulting HashMap is immutable. Thus, it remains empty forever.

Creating a HashMap using Google Guava

Google’s Guava Library provides several useful abstractions and utility methods to work with the Java Collections framework. Let’s see how the Guava Library helps to initialize mutable and immutable HashMap instances inline.

Immutable HashMap using Guava

Guava’s ImmutableMap class implements Java Map, representing an immutable HashMap. The class provides the of() method, a factory method that creates an immutable Java HashMap containing the given key-value pairs.
Example of initializing an immutable Java HashMap using Google Guava.

Map immutableMap = ImmutableMap .of("color", "pink", "drink", "coffee", "shape", "slim");Code language: Java (java)

Mutable HashMap using Guava

The Maps class of Guava is a static utility class with useful abstractions. The newHashMap() method of the Maps class returns a mutable HashMap instance containing all the elements of the given Map.
Example of initializing a mutable Java HashMap using Google Guava.

Map immutableMap = ImmutableMap .of("color", "pink", "drink", "coffee", "shape", "slim"); Map mutuableMap = Maps.newHashMap(immutableMap);Code language: Java (java)

Although we provide an immutable Map, the newHashMap() method always returns a mutable HashMap.

Creating a HashMap using Stream Collectors

The Java Collectors class provide a collector abstraction that collects the Stream elements and forms a Java HashMap.

Example of initializing a Java HashMap using Stream Collectors.

List colors = List.of("Pink", "Red", "Black"); Map map = colors.stream() .collect(Collectors .toMap(String::toUpperCase, String::toLowerCase)); System.out.println(map); //prints: // Code language: Java (java)

Creating a HashMap using Factory Method

Java 9 introduced factory methods to the Map interface that we can use to do inline initialization of Java HashMap instances.

Using the Factory Method of()

The of() method of the Map interface accepts key-value pairs in the form of varargs and returns a new immutable HashMap containing the elements.
Example of initializing Java HashMap inline using factory methods.

Map immutableMap = Map.of("color", "black", "drink","coffee");Code language: Java (java)

Please note that the Map interface has ten overloaded versions of the of() method.

static Map of (K k1, V v1); static Map of (K k1, V v1, K k2, V v2); static Map of (K k1, V v1, K k2, V v2, K k3, V v3); static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4); static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5); static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6); static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7); static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8); static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9); static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10); Code language: Java (java)

This is why we can only use the factory method of() to create an inline HashMap of up to ten key-value pairs.

Using the Factory Method ofEntries()

Alternatively, the ofEntries() method of the Map method accepts n key-value pairs and can initialize a HashMap of infinite elements.

Example of initializing inline Java HashMap using Map ofEntries() method.

Map ofEntries = Map.ofEntries( Map.entry("color", "pink"), Map.entry("drink", "coffee") );Code language: Java (java)

Summary

This article demonstrated different ways of creating mutable and immutable Java HashMap instances and adding key-value pairs in the same line. We used Java Map factory methods, Collections class, and the Guava Library to initialize the Maps inline.

Please refer to our GitHub Repository for the complete source code of the examples.

Источник

Initialize Map in Java

This post will discuss various methods to initialize a map in Java.

Java is often criticized for its verbosity. For example, creating a map containing involves constructing it, storing it in a variable, invoking the put() method on it several times, and then maybe wrapping it to make it unmodifiable:

This post will discuss various methods to initialize a map in a single expression.

1. Using Java Collections

The Collections class consists of several static factory methods that operate on collections and return a new collection backed by a specified collection.

The Collections class provides an unmodifiableMap() method that takes another map and wraps it in a class that rejects modification requests, thus creating an unmodifiable view of the original map. Any attempts to modify the returned map will result in an UnsupportedOperationException .

But it won’t create an inherently unmodifiable map. Instead, possession of a reference to the underlying collection still allows modification. Also, each wrapper is an additional object, requiring another level of indirection and consuming more memory than the original collection. Finally, the wrapped collection still bears the expense of supporting mutation even if it is never intended to be modified.

There are existing factories in the Collections class to produce a singleton Map with exactly one key-value pair.

We can use Collections.singletonMap() that returns an immutable map containing specified key-value pair. The map will throw an UnsupportedOperationException if any modification operation is performed on it.

We can use Collections.EMPTY_MAP that returns a serializable and immutable empty map.

The above method might throw an unchecked assignment warning. The following example demonstrates the type-safe way to obtain an empty map:

2. Using Java 8

We can use the Java 8 Stream to construct small maps by obtaining stream from static factory methods like Stream.of() or Arrays.stream() and accumulating the input elements into a new map using collectors.

A stream is essentially a sequence of items, not a sequence of key/value pairs. It is illogical to think that we can just take a stream and construct a map out of it without specifying how to extract keys and values. We can use the Collectors.toMap() method to specify it.

Collectors.toMap() returns a Collector that accumulates elements into a map whose keys and values result from applying the provided mapping functions to the input elements.

To initialize a map with different types for key and value, for instance Map , we can do:

Another approach that can easily accommodate different types for key and value involves creating a stream of map entries. There are two implementations of the Map.Entry interface:

We could also adapt a collector to perform an additional finishing transformation. For example, we could adapt the toMap() collector to always produce an immutable map with:

> ) . collect ( Collectors . collectingAndThen ( Collectors . toMap ( p -> p [ 0 ] , p -> p [ 1 ] ) ,

3. Using Double Brace Initialization

Another alternative is to use “Double Brace Initialization”. This creates an anonymous inner class with an instance initializer in it. We should avoid this technique at all costs as it creates an extra class at each usage. It also holds hidden references to the enclosing instance and any captured objects. This may cause memory leaks or problems with serialization.

Источник

Оцените статью