What is the method to initialize a map and assign values in Java?
In Java, there are several ways to initialize a Map and assign values to it:
- Create a HashMap using its constructor.
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
- Utilizing static initialization block:
Map<String, Integer> map = new HashMap<String, Integer>(){{
put("key1", 1);
put("key2", 2);
}};
- Use the Map.of method in Java 9.
Map<String, Integer> map = Map.of("key1", 1, "key2", 2);
- Utilize the Map.ofEntries method in Java 9:
Map<String, Integer> map = Map.ofEntries(
entry("key1", 1),
entry("key2", 2)
);
You can initialize a Map and assign values to it using any method.