Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define Map contents on initialisation? [duplicate]

I was just wondering if it is possible to define the contents of a Map Object on initialisation.

For example, an array can be created, as:

new String[] {“apples”, “bananas”, “pears”}

So, I was wondering if there is something similar we can do for maps.

like image 355
Larry Avatar asked Jan 30 '11 13:01

Larry


People also ask

How do you manually define a map in Java?

Map map = new HashMap(); map. put("key1", "value 1"); String element1 = (String) map. get("key1"); Notice that the get() method returns a Java Object , so we have to cast it to a String (because we know the value is a String).

How do you initialize a map list?

The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};

How do you define a map in Java?

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.


1 Answers

You can, sort of, using this syntax trick:

Map<String,String> map = new HashMap<String,String>() {{
    put("x", "y");
    put("a", "b");
}};

Not very pleasant, though. This creates an anonymous subclass of HashMap, and populates it in the instance initializer.

like image 126
skaffman Avatar answered Oct 13 '22 15:10

skaffman