Initialize HashMap in Java
Last Updated :
11 Jul, 2025
HashMap in Java is a part of the java.util package and allows storing key-value pairs. Initializing a HashMap can be done in multiple ways, including static blocks, utility methods from the Collections class, and modern approaches provided by Java 8 and Java 9. This article will guide you through these methods with clear examples and explanations.
Different Methods to Initialize a HashMap in Java
- Using Static Block
- Using Collections
- Using Java 8 Methods (Streams)
- Using Java 9 Methods (Map.of() and Map.ofEntries())
1. Initialize HashMap Using Static Block
Using a static block is an effective way to initialize a HashMap at class loading time, especially when we need a constant, unmodifiable map.
Example:
Java
// Java Program to Initialize a HashMap Using Static Block
import java.util.HashMap;
import java.util.Map;
public class StaticBlockInitialization {
private static final Map<Integer, String> map;
static {
map = new HashMap<>();
map.put(1, "C");
map.put(2, "C++");
map.put(3, "Java");
}
public static void main(String args[])
{
System.out.println("HashMap initialized using static block: " + map);
}
}
OutputHashMap initialized using static block: {1=C, 2=C++, 3=Java}
Explanation:
- The static block runs when the class is loaded.
- HashMap
map
is initialized and populated with key-value pairs. - This approach is suitable for creating immutable maps that remain constant throughout the program's execution.
2. Initialize HashMap Using Collections
Java Collections framework provides utility methods to initialize a HashMap. One such method is Collections.singletonMap, which creates a map with a single entry. This map can be used to initialize a HashMap.
Example:
Java
// Java Program to Initialize a HashMap Using Collections
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class CollectionsInitialization {
public static void main(String args[])
{
Map<Integer, String> singletonMap = Collections.singletonMap(1, "C");
// Creating a mutable map
Map<Integer, String> map = new HashMap<>(singletonMap);
map.put(2, "C++");
map.put(3, "Java");
System.out.println("HashMap initialized using Collections: " + map);
}
}
OutputHashMap initialized using Collections: {1=C, 2=C++, 3=Java}
Explanation:
- Collections.singletonMap creates an immutable map with a single entry.
- This map is used to initialize a mutable HashMap which can be further modified.
3. Initialize HashMap Using Java 8 Methods (Using Stream)
Java 8 introduced Streams, which can be used to initialize a HashMap using arrays of key-value pairs.
Example:
Java
//Java Program to Initialize a HashMap Using Stream
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamInitialization {
public static void main(String args[])
{
Map<Integer, String> map = Stream.of(new Object[][] {
{ 1, "C" },
{ 2, "C++" },
{ 3, "Java" },
}).collect(Collectors.toMap(data -> (Integer) data[0], data -> (String) data[1]));
System.out.println("HashMap initialized using Java 8 Stream: " + map);
}
}
OutputHashMap initialized using Java 8 Stream: {1=C, 2=C++, 3=Java}
Explanation:
- Stream.of creates a stream of object arrays, each containing a key-value pair.
- Collectors.toMap collects the stream elements into a HashMap.
4. Initialize HashMap Using Java 9 Methods
Java 9 introduced convenient factory methods like Map.of and Map.ofEntries for initializing HashMaps.
Example Using Map.of():
Java
//Java Program to Initialize a HashMap Using Map.of()
import java.util.Map;
public class Java9Initialization {
public static void main(String[] args) {
// Using Map.of for up to 10 key-value pairs
Map<Integer, String> map1 = Map.of(1, "C", 2, "C++", 3, "Java");
System.out.println("HashMap initialized using Java 9 Map.of: " + map1);
}
}
OutputHashMap initialized using Java 9 Map.of: {1=C, 2=C++, 3=Java}
Explanation:
- Map.of creates an immutable map with up to 10 key-value pairs.
Example Using Map.ofEntries():
Java
//Java Program to Initialize a HashMap using Map.ofEntries()
import java.util.Map;
public class Java9Initialization {
public static void main(String[] args) {
// Using Map.ofEntries for more than 10 key-value pairs
Map<Integer, String> map2 = Map.ofEntries(
Map.entry(1, "C"),
Map.entry(2, "C++"),
Map.entry(3, "Java")
);
System.out.println("HashMap initialized using Java 9 Map.ofEntries: " + map2);
}
}
OutputHashMap initialized using Java 9 Map.ofEntries: {1=C, 3=Java, 2=C++}
Explanation:
Map.ofEntries
allows creating an immutable map with more than 10 entries using Map.entry
for each key-value pair.
Similar Reads
HashMap in Java In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding
15+ min read
Internal Working of HashMap in Java In this article, we will understand the internal workings of the HashMap in Java, also how the get() and put() method functions, how hashing is done, how key-value pairs are stored, and how the values are retrieved by keys.Basic Structure of a HashMapHashMap contains an array of Node objects. Each n
10 min read
Initialize a static map in Java with Examples In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Method 1: Creating a static map variable. Instantiating it in a static block. Below is the implementati
1 min read
Hashtable in Java Hashtable class, introduced as part of the Java Collections framework, implements a hash table that maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method an
12 min read
ConcurrentMap Interface in Java The ConcurrentMap Interface is part of the Java Collections Framework and was introduced in JDK 1.5. It is designed for thread-safe concurrent access to its entries without compromising the consistency of the map. The interface resides in the java.util.concurrent package and extends the Map interfac
9 min read
ConcurrentHashMap in Java In Java, the ConcurrentHashMap is a thread-safe implementation of the Map interface. It allows multiple threads to read and write data simultaneously, without the need for locking the entire map. Unlike a regular HashMap, which is not thread-safe, ConcurrentHashMap ensures that the operations are th
15+ min read