Question:
Is it possible to initialize a Java HashMap in a concise way like this?
Map<String,String> test = new HashMap<String, String>{"test":"test","test":"test"};
If so, what is the correct syntax?
Answer for Java Version 9 or higher:
Yes, this is now possible using factory methods added in Java 9:
// For up to 10 elements Map<String, String> test1 = Map.of("a", "b", "c", "d"); // For any number of elements import static java.util.Map.entry; Map<String, String> test2 = Map.ofEntries(entry("a", "b"), entry("c", "d"));
Answer for up to Java Version 8:
Unfortunately, direct initialization in the provided syntax is not possible. However, you can use an anonymous subclass to shorten the code:
Map<String, String> myMap = new HashMap<String, String>() {{ put("a", "b"); put("c", "d"); }};
Alternatively, you can create a function for initialization:
Map<String, String> myMap = createMap(); private static Map<String, String> createMap() { Map<String,String> myMap = new HashMap<String,String>(); myMap.put("a", "b"); myMap.put("c", "d"); return myMap; }
The above is the detailed content of How to Initialize a Java HashMap Directly?. For more information, please follow other related articles on the PHP Chinese website!