RichyJ89
RichyJ89

Reputation: 47

Good design pattern choice for initializing a hashmap in Java

I have a non-static class in Java that has a static hashmap field. The hashmap should be initialized with some key-value pairs generated by code. The hashmap is not to be changed after that.

How should this be achieved? Should I just create a static init method and make sure to run this once before using the class, or are there better ways of doing it?

Upvotes: 2

Views: 907

Answers (2)

Robert Balent
Robert Balent

Reputation: 1462

You can easily create immutable maps with Google Guava library:

private static Map<String, String> map = ImmutableMap.of(
    "key1", "value1",
    "key2", "value2");

If you want to use it for many values then builder() is provided.

Upvotes: 0

Trevor Freeman
Trevor Freeman

Reputation: 7242

You can use a static initializer block in your class.

e.g.

private static Map<String, String> myMap;
static {
    HashMap<String,String> map = new HashMap<String,String>();
    map.put("foo","bar");

    myMap = Collections.unmodifiableMap(map);
}

Upvotes: 5

Related Questions