Vishwa Ratna
Vishwa Ratna

Reputation: 6390

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?

Upvotes: 5

Views: 1599

Answers (2)

Andronicus
Andronicus

Reputation: 26046

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.

Upvotes: 5

Ruslan
Ruslan

Reputation: 6290

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"))
);

Upvotes: 9

Related Questions