Search code examples
javahashtable

writing an initialized static hashtable elegantly


Is there a way to write a static final Hashtable in java in key value pairs just like you can initialize a string array conveniently as :

String [] foo = {"A","AB"};

Basically what I mean is not having to write the words "put" for key:value pairs but instead may be something like:

Hashtable<String, String> foo = {"JJ":"222","KK":"222"}

which IMO looks more elegant.

(I know the initialization would need to be in a static block. I am leaving that out for now)


Solution

  • No, Java doesn't have map literals, but it does have array literals.

    static final Map<String, String> map;
    
    static {
        map = new HashMap<String, String>();
        String[][] pairs = {
            {"foo", "bar"},
            {"x", "y"}
        };
        for (String[] pair : pairs) {
            map.put(pair[0], pair[1]);
        }
    }
    

    Of course this doesn't really add anything to the straightforward copy and paste put solution, and it doesn't work well if your key and value types aren't the same.