Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The way to instantiate map<String, List<String>> in Java

I would like to instantiate Map<String, List<String>> in Java,

I tried

Map<String, List<String>> foo = new <String, List<String>>();

and

Map<String, List<String>> foo = new <String, ArrayList<String>>();

None of them work. Does any one know how to instantiate this map in Java?

like image 405
Alfred Zhong Avatar asked Aug 13 '13 22:08

Alfred Zhong


People also ask

How do you initialize a map list?

Let's create a map of string as key and int as value and initialize it with initializer_list i.e. }; std::initializer_list<std::pair<const std::string, int> > = { {"Riti",2}, {"Jack",4} }; std::initializer_list<std::pair<const std::string, int> > = { {"Riti",2}, {"Jack",4} };

How do you initialize a string object map in Java?

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

Can we create map with list in Java?

toMap() method: This method includes creation of a list of the student objects, and uses Collectors. toMap() to convert it into a Map.


1 Answers

new HashMap<String, List<String>>();

or as gparyani commented:

new HashMap<>(); // type inference

Note: each entry needs to be given an instantiated List as a value. You cannot get("myKey").add("some_string_for_this_key"); the very first time you get() a List from it.

So, fetch a List, check if it's null.

If it's null, make a new list, add the string to it, put the List back. If it's anything but null, add to it, or do what you want.

like image 147
Xabster Avatar answered Oct 22 '22 05:10

Xabster