Java – How do I define a static dictionary and access it in Java?

How do I define a static dictionary and access it in Java?… here is a solution to the problem.

How do I define a static dictionary and access it in Java?

How to define a static dictionary and access it in Java.
I do this in iOS Swift:

let pairs = [
     "Name1": "Value1", 
     "Name2": "Value2"
]

print(pairs["Name1"]) // Value1

How to do something like this in Java?

Solution

You can also initialize the map in a static block.

public class YourClass {

public static final Map<String, String> staticMap = new HashMap<>();

static {
      staticMap.put("key1", "value1");
      staticMap.put("key2", "value2");
  }

}

Related Problems and Solutions