Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a best practice for writing maps literal style in Java?

In short, if you want to write a map of e.g. constants in Java, which in e.g. Python and Javascript you would write as a literal,

T<String,String> CONSTANTS = {     "CONSTANT_NAME_0": CONSTANT_VALUE_0 ,     "CONSTANT_NAME_1": CONSTANT_VALUE_1 ,     "CONSTANT_NAME_2": CONSTANT_VALUE_2 ,     //... } ; 

is there a Class or any preset Object that you can use for writing a data structure like that?

like image 614
FK82 Avatar asked Sep 26 '10 13:09

FK82


People also ask

Which map is best in Java?

HashMap is a key and value collection in java. The HashMap stores the data in key and value format. It provides the basic implementation of the Map interface of Java.

What is the difference between HashMap and map in Java?

HashMap is a non-synchronized class of the Java Collection Framework that contains null values and keys, whereas Map is a Java interface, which is used to map key-pair values.

Can HashMap be static?

2. The Static Initializer for a Static HashMap. The advantage of this kind of initialization is that the map is mutable, but it will only work for static. Consequently, entries can be added and removed as and when required.


2 Answers

I like to do it this way:

Map map = new HashMap() {{     put("foo", "bar");     put(123, 456); }}; 

The double {{ }} are an instance initialization block. They are a bit unusual but they are useful. No need for libraries or helpers.

like image 57
xpmatteo Avatar answered Oct 08 '22 21:10

xpmatteo


No, Java doesn't have a map literal. The closest you'll come to this is using Google Collections' ImmutableMap:

Map<K,V> CONSTANTS = ImmutableMap.of(     NAME_1, VALUE_1,     NAME_2, VALUE_2     //etc.   ); 
like image 27
Jorn Avatar answered Oct 08 '22 21:10

Jorn