How to define a static dictionary and access it in Java. I do it like this in iOS Swift:
let pairs = [
"Name1": "Value1",
"Name2": "Value2"
]
print(pairs["Name1"]) // Value1
How to do something like this in Java?
Dictionary has a direct child class Hashtable. So for creating a dictionary in Java you can use Hashtable. This class implements a hash table, which maps keys to values and any non-null object can be used as a key or as a value. In Java hierarchy Hashtable extends Dictionary and implements Map.
A Java dictionary is an abstract class that stores key-value pairs. Given a key, its corresponding value can be stored and retrieved as needed; thus, a dictionary is a list of key-value pairs. The Dictionary object classes are implemented in java.
In Java, to deal with the key-value pair, the Map interface and its implementation classes are used. We can use classes such as HashMap and TreeMap to store data into the key-value pair. Apart from these built-in classes, we can create our own class that can hold the key-value pair.
You could initialize the map inside static
block, too.
public class YourClass {
public static final Map<String, String> staticMap = new HashMap<>();
static {
staticMap.put("key1", "value1");
staticMap.put("key2", "value2");
}
}
Look at Guavas ImmutableMap for a constant dictionary.
private static final Map<String, String> PAIRS = ImmutableMap.of("Name1", "Value1","Name2", "Value2");
If you have lots of entries you can use the
ImmutableMap.builder()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With