Ways to Initialize HashMap Collection in Java

The preferred way to initialize a HashMap in Java is by using the default constructor and instantiating it as a Map interface.

Map<String, String> map = new HashMap<>();

As Map is an interface in Java, map variable here can store an instance of any class that implements the Map interface, such as HashMap. This allows for flexibility and code maintainability, as you can switch to a different implementation of the Map interface without changing the rest of your code.

Note: In this way, you get a mutable map that is prone to concurrent modifications in multithreaded environments.

Initialize HashMap as an Immutable Map

Map<String, String> map = Collections.unmodifiableMap(map);

Using Java 8 Streams

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class HashMapUsingStreams {

    public static void main(String[] args) {
        Map<String, String> countryCapitalMap = Stream.of(new String[][] {
                { "USA", "Washington, D.C." },
                { "Canada", "Ottawa" },
                { "France", "Paris" },
                { "Germany", "Berlin" },
                { "Japan", "Tokyo" }
        }).collect(Collectors.toMap(data -> data[0], data -> data[1]));

Java HashMap using Streams

Java 9 or later: Using Initialization with Values

HashMap<KeyType, ValueType> hashMap = new HashMap<>(Map.of(
    key1, value1,
    key2, value2,
    key3, value3

another way!

HashMap<KeyType, ValueType> hashMap = new HashMap<>(Map.ofEntries(
    entry(key1, value1),
    entry(key2, value2),
    entry(key3, value3)

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap