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

14,449

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

Sorry, I'm a tinkerer :-) Here's a somewhat cleaner way.

public class MapTest {
    private static Map<String, String> map;

    static {
        Map<String, String> tmpMap = new HashMap<String, String>();

        tmpMap.put("A", "Apple");
        tmpMap.put("B", "Banana");
        // etc
        map = Collections.unmodifiableMap(tmpMap);
    }

    public Map<String, String> getMap() {
        return map;
    }
}

Solution 5

You can write yourself a quick helper function:

@SuppressWarnings("unchecked")
public static <K,V> Map<K,V> ImmutableMap(Object... keyValPair){
    Map<K,V> map = new HashMap<K,V>();

    if(keyValPair.length % 2 != 0){
        throw new IllegalArgumentException("Keys and values must be pairs.");
    }

    for(int i = 0; i < keyValPair.length; i += 2){
        map.put((K) keyValPair[i], (V) keyValPair[i+1]);
    }

    return Collections.unmodifiableMap(map);
}

Note the code above isn't going to stop you from overwriting constants of the same name, using CONST_1 multiple places in your list will result in the final CONST_1's value appearing.

Usage is something like:

Map<String,Double> constants = ImmutableMap(
    "CONST_0", 1.0,
    "CONST_1", 2.0
);
Share:
14,449
FK82
Author by

FK82

Updated on June 05, 2022

Comments

  • FK82
    FK82 almost 2 years

    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?