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.
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]));
System.out.println(countryCapitalMap);
}
}

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)
));
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!