What is the method for initializing and assigning values in a map in Java?
In Java, there are various ways to initialize and assign values to a Map object. Here are some common methods:
- Initialize and assign values literally.
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
- Initializing and assigning values using the constructor of the implementing class of Map.
Map<String, Integer> map = new HashMap<>(Map.of("key1", 1, "key2", 2));
Alternatively:
Map<String, Integer> map = new HashMap<>(Map.ofEntries(
Map.entry("key1", 1),
Map.entry("key2", 2)
));
- add all items to the collection
Map<String, Integer> originalMap = new HashMap<>();
originalMap.put("key1", 1);
originalMap.put("key2", 2);
Map<String, Integer> newMap = new HashMap<>();
newMap.putAll(originalMap);
- Flow continuously in a particular direction.
Map<String, Integer> map = Stream.of(
new AbstractMap.SimpleEntry<>("key1", 1),
new AbstractMap.SimpleEntry<>("key2", 2)
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
These are some common methods, so you can choose the appropriate initialization and assignment methods based on specific needs and usage scenarios.