Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a static dictionary and access it in Java?

Tags:

java

android

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?

like image 841
The Cook Avatar asked Dec 09 '16 11:12

The Cook


People also ask

How do you declare a dictionary 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.

Is dictionary available in Java?

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.

How do you pass a key-value pair 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.


2 Answers

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");
  }

}
like image 84
Héctor Avatar answered Sep 22 '22 19:09

Héctor


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()
like image 27
Gee2113 Avatar answered Sep 23 '22 19:09

Gee2113