实例化map< String,List< String>>的方式为:在Java中 [英] The way to instantiate map<String, List<String>> in Java

查看:145
本文介绍了实例化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.

这篇关于实例化map&lt; String,List&lt; String&gt;&gt;的方式为:在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆