Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use double brace initialization for Map of Map

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?

like image 319
Vishwa Ratna Avatar asked Mar 12 '19 10:03

Vishwa Ratna


People also ask

What is the use of double brace initialization in Java?

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.

How to initialize a map in Java?

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: // ...

Is it safe to use a brace to initialize a list?

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

How to initialize a map with values in a single expression?

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.


2 Answers

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"))
);
like image 123
Ruslan Avatar answered Nov 04 '22 06:11

Ruslan


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.

like image 22
Andronicus Avatar answered Nov 04 '22 08:11

Andronicus