Home >Java >javaTutorial >How to Efficiently Initialize a HashMap in Java?
Many Java developers desire a straightforward way to initialize a HashMap with key-value pairs. Unfortunately, Java's standard library lacks a syntax that directly accommodates this.
However, for Java 9 and later, there's good news! New factory methods have been introduced to simplify map creation:
Example:
// Using Map.of for up to 10 elements Map<String, String> test1 = Map.of("a", "b", "c", "d"); // Using Map.ofEntries for any number of elements Map<String, String> test2 = Map.ofEntries(entry("a", "b"), entry("c", "d"));
For earlier Java versions, you'll need to manually add each element. Here's a slightly more concise option using an anonymous subclass initializer:
Example:
Map<String, String> myMap = new HashMap<>() {{ put("a", "b"); put("c", "d"); }};
Note:
An alternative involving a function:
Example:
Map<String, String> myMap = createMap(); private static Map<String, String> createMap() { Map<String,String> myMap = new HashMap<>(); myMap.put("a", "b"); myMap.put("c", "d"); return myMap; }
The above is the detailed content of How to Efficiently Initialize a HashMap in Java?. For more information, please follow other related articles on the PHP Chinese website!