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?
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} };
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"); }};
toMap() method: This method includes creation of a list of the student objects, and uses Collectors. toMap() to convert it into a Map.
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.
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