This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/6…
Issue an overview
Is there a straightforward way to generate a HashMap?
Map<String,String> test =
new HashMap<String, String>{"test":"test"."test":"test"};
Copy the code
You don’t have to go through this
Map<String,String> test =
new HashMap<String, String>();
test.put("test"."test")
Copy the code
Best answer
For all versions: If you only need a constant key-value pair for map you can do as follows:
Map<String,String> test = Collections.singletonMap("key"."value");
Copy the code
For java9.0 and above: if you can:
/ / attention! This method cannot exceed 10 key-value pairs
Map<String, String> test1 = Map.of(
"a"."b"."c"."d"
);
// There is no limit to the number of methods
import static java.util.Map.entry;
Map<String, String> test2 = Map.ofEntries(
entry("a"."b"),
entry("c"."d"));Copy the code
For java8.0 and below: you cannot do this, but you can make the statement a little shorter by using methods of anonymous inner classes.
Map<String, String> myMap = new HashMap<String, String>() {{
put("a"."b");
put("c"."d");
}};
Copy the code
But anonymous inner classes sometimes have unexpected glitches, such as:
- Takes up extra memory and has startup time for object creation.
- It affects garbage collection of external classes, blocking more space.
Total knot
For Java versions below 9.0, simply write PUT
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;
}
Copy the code
New features are available for Java 9.0 and above!