且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建ArrayList的一个HashMap的***方法

更新时间:2022-02-13 22:22:39

您不需要重新添加的ArrayList回你的地图。如果ArrayList中已经存在,那么你的价值只是添加到它。

You don't need to re-add the ArrayList back to your Map. If the ArrayList already exists then just add your value to it.

这是改进执行可能看起来像:

An improved implementation might look like:

Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();

在处理每一行:

String user = user field from line
String value = value field from line

Collection<String> values = map.get(user);
if (values==null) {
    values = new ArrayList<String>();
    map.put(user, values)
}
values.add(value);

后续2014年4月 - 我写的原来的答复早在2009年时,我的谷歌番石榴的知识是有限的。在所有的光,谷歌番石榴呢,我现在建议使用其 Multimap之,而不是重新创造它。

Follow-up April 2014 - I wrote the original answer back in 2009 when my knowledge of Google Guava was limited. In light of all that Google Guava does, I now recommend using its Multimap instead of reinvent it.

Multimap<String, String> values = HashMultimap.create();
values.put("user1", "value1");
values.put("user2", "value2");
values.put("user3", "value3");
values.put("user1", "value4");

System.out.println(values.get("user1"));
System.out.println(values.get("user2"));
System.out.println(values.get("user3"));

输出:

[value4, value1]
[value2]
[value3]