实例化map< String,List< String>>的方式为:在Java中
我想实例化Java中的 Map< String,List< String>>
I would like to instantiate Map<String, List<String>>
in Java,
我尝试过
Map<String, List<String>> foo = new <String, List<String>>();
和
Map<String, List<String>> foo = new <String, ArrayList<String>>();
它们都不起作用.有人知道如何用Java实例化此映射吗?
None of them work. Does any one know how to instantiate this map in Java?
new HashMap<String, List<String>>();
或gparyani评论:
or as gparyani commented:
new HashMap<>(); // type inference
注意:每个条目都需要被实例化为值的列表.您不能get("myKey").add("some_string_for_this_key");第一次从列表中获取列表.
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.
如果为空,则创建一个新列表,向其中添加字符串,然后将列表放回去.如果它不是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.