The most popular solution is almost Guava ImmutableMap . (Disclosure: I contribute to Guava.)
Map<Integer, String> map = ImmutableMap.of(
1, "one",
2, "two");
or
ImmutableMap<Integer, String> map = ImmutableMap
.<Integer, String> builder()
.put(1, "one")
.put(2, "two")
.build();
Without other libraries, the only workaround other than the one you wrote is
static final Map<Integer, String> CONSTANT_MAP;
static {
Map<Integer, String> tmp = new LinkedHashMap<Integer, String>();
tmp.put(1, "one");
tmp.put(2, "two");
CONSTANT_MAP = Collections.unmodifiableMap(tmp);
}
source
share