writing an initialized static hashtable elegantly

An anonymous inner class would give you double brace initialization, which is useful in some cases:

static final Map<String, String> map = new HashMap<String, String>() {{
    put("foo", "bar");
    put("x", "y");
}};

In any case, @michael667's answer is probably the best


You can use guava's ImmutableMap:

map = ImmutableMap.of(key1, value1, key2, value2);

These convenience methods exist for one to five elements. If you need more, you can use an ImmutableMap.Builder:

static final ImmutableMap<String, Integer> WORD_TO_INT =
   new ImmutableMap.Builder<String, Integer>()
     .put("one", 1)
     .put("two", 2)
     .put("three", 3)
     .build();

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.

Tags:

Java

Hashtable