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

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.


Constants? I'd use an enum.

public enum Constants { 
    NAME_1("Value1"),
    NAME_2("Value2"),
    NAME_3("Value3");

    private String value;

    Constants(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}

Value for e.g. NAME_2 can be obtained as follows:

String name2value = Constants.NAME_2.value();

Only give the enum a bit more sensible name, e.g. Settings, Defaults, etc, whatever those name/value pairs actually represent.


No, Java doesn't have a map literal. The closest you'll come to this is using Google Collections' ImmutableMap:

Map<K,V> CONSTANTS = ImmutableMap.of(
    NAME_1, VALUE_1,
    NAME_2, VALUE_2
    //etc.
  );