I do understand that double brace initialization has its own hidden cost, still is there a possible way to initialize Map<String,Map<String,String>>()
.
What i tried:
Map<String, Map<String, String>> defaultSourceCode = new HashMap<String, Map<String, String>>(){
{"a",new HashMap<String, String>(){{"c","d"}}}
};
I know it is a bad practice but as for experiment i am trying it.
Reference and Motivation: Arrays.asList also for maps?
In Double brace initialization { { }}, first brace creates a new Anonymous Inner Class, the second brace declares an instance initializer block that is run when the anonymous inner class is instantiated. This approach is not recommended as it creates an extra class at each usage.
When you want to initialize a Map, for example, you need a sequence of statements: This is especially a problem when the Map is a static final member; you’d need a static initializer block to initialize it, making the code even more verbose: // ...
The first brace creates a new Anonymous Class and the second set of brace creates an instance initializers like the static block. Like others have pointed, it's not safe to use. However, you can always use this alternative for initializing collections. Java 8 List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C")); Java 9
It is possible to initialize a Map with values in a single expression if you are using Java 9 or higher version using Map.of () and Map.ofEntries () method. This is shortest possible way so far.
You can use Map.of()
from java9 that returns an immutable map:
Map<String, Map<String, String>> map = Map.of("a", Map.of("c", "d"));
Or Map.ofEntries
:
Map<String, Map<String, String>> map1 = Map.ofEntries(
Map.entry("a", Map.of("c", "d"))
);
Almost everything is fine, you just have to use method calls in double braces:
Map<String, Map<String, String>> defaultSourceCode = new HashMap<String, Map<String, String>>(){
{put("a",new HashMap<String, String>(){{put("c","d");}});}
};
But this answer describes, why you shouldn't do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With