How to directly initialize a HashMap in Java?
To directly initialize a HashMap in Java, you can use the put()
method to add elements to the map. Here's an example:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
This creates a HashMap with three key-value pairs: {"key1", 1}
, {"key2", 2}
, and {"key3", 3}
.
Alternatively, you can use the putAll()
method to add all of the elements from another map to the HashMap:
Map<String, Integer> map1 = new HashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
Map<String, Integer> map2 = new HashMap<>();
map2.put("key3", 3);
map2.put("key4", 4);
map1.putAll(map2);
This creates a map1
with four key-value pairs: {"key1", 1}
, {"key2", 2}
, {"key3", 3}
, and {"key4", 4}
.
You can also use the HashMap constructor that takes a Map
as an argument to create a new HashMap and initialize it with the elements from another map:
Map<String, Integer> map1 = new HashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
Map<String, Integer> map2 = new HashMap<>(map1);
This creates a new map2
with the same key-value pairs as map1
.
Finally, you can use the Map.of()
method to create an immutable map with a fixed set of elements:
Map<String, Integer> map = Map.of("key1", 1, "key2", 2, "key3", 3);
This creates an immutable map with three key-value pairs: {"key1", 1}
, {"key2", 2}
, and {"key3", 3}
.