Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a public static final read-only LinkedMap (bidirectionnal map)

I would like to create a

public static final LinkedMap myMap;

Somewhere I found something similar for Maps:

 public class Test {
        private static final Map<Integer, String> MY_MAP = createMap();

        private static Map<Integer, String> createMap() {
            Map<Integer, String> result = new HashMap<Integer, String>();
            result.put(1, "one");
            result.put(2, "two");
            return Collections.unmodifiableMap(result);
        }
    }

But I cannot apply the 'unmodifiableMap' method it to a LinkedMap. Can anybody help me? Is it possible at all?

like image 284
Antje Janosch Avatar asked May 16 '12 08:05

Antje Janosch


People also ask

How to initialize static map in Java?

The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};

Can we make a map static in Java?

We can use Java 8 Stream to construct static maps by obtaining stream from static factory methods like Stream.

What is static initializer in Java?

A Static Initialization Block in Java is a block that runs before the main( ) method in Java. Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.


1 Answers

The most popular workaround is almost certainly a 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've written 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);
}
like image 84
Louis Wasserman Avatar answered Sep 22 '22 19:09

Louis Wasserman