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:

  1. Create a HashMap using its constructor.
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
  1. Utilizing static initialization block:
Map<String, Integer> map = new HashMap<String, Integer>(){{
    put("key1", 1);
    put("key2", 2);
}};
  1. Use the Map.of method in Java 9.
Map<String, Integer> map = Map.of("key1", 1, "key2", 2);
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds