Is there a best practice for writing maps literal style in Java?

FK82 picture FK82 · Sep 26, 2010 · Viewed 13.8k times · Source

In short, if you want to write a map of e.g. constants in Java, which in e.g. Python and Javascript you would write as a literal,

T<String,String> CONSTANTS =
{
    "CONSTANT_NAME_0": CONSTANT_VALUE_0 ,
    "CONSTANT_NAME_1": CONSTANT_VALUE_1 ,
    "CONSTANT_NAME_2": CONSTANT_VALUE_2 ,
    //...
} ;

is there a Class or any preset Object that you can use for writing a data structure like that?

Answer

xpmatteo picture xpmatteo · Mar 4, 2011

I like to do it this way:

Map map = new HashMap() {{
    put("foo", "bar");
    put(123, 456);
}};

The double {{ }} are an instance initialization block. They are a bit unusual but they are useful. No need for libraries or helpers.