Java HashMap Initialization Guide
In Java, you can initialize and assign values to a HashMap object using the constructor and put method.
Option 1: Initialize and assign values using a constructor method.
Map<String, Integer> map = new HashMap<String, Integer>() {{
put("key1", 1);
put("key2", 2);
put("key3", 3);
}};
Option 2: Add key-value pairs one by one using the put method.
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
Both methods can be used to initialize and assign values to a HashMap object. The first method uses double braces initialization, which allows you to directly add key-value pairs during initialization, making it more concise. The second method involves adding key-value pairs one by one, making it more straightforward.