创建ArrayList的一个HashMap的最佳方法 [英] Best way to create a hashmap of arraylist
问题描述
我在.txt格式的数据的一百万行。格式是非常简单的。对于每一行:
I have one million rows of data in .txt format. the format is very simple. For each row:
user1,value1
user2,value2
user3,value3
user1,value4
...
您知道我的意思。对于每个用户,它可以出现多次,或只出现一次(你永远不知道)。我需要找出每个用户所有的值。因为用户可能会随机出现,我用的Hashmap做到这一点。这就是:HashMap的(键:字符串值:ArrayList中)。但是,将数据添加到ArrayList,我必须不断地使用HashMap中获得(键)来获得ArrayList中,增加价值,然后把它放回去到HashMap中。我觉得这不是很有效。任何人都知道一个更好的方式来做到这一点?
You know what I mean. For each user, it could appear many times, or appear only once (you never know). I need to find out all the values for each user. Because user may appear randomly, I used Hashmap to do it. That is: HashMap(key: String, value: ArrayList). But to add data to the arrayList, I have to constantly use HashMap get(key) to get the arrayList, add value to it, then put it back to HashMap. I feel it is not that very efficient. Anybody knows a better way to do that?
推荐答案
您不需要重新添加的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]
这篇关于创建ArrayList的一个HashMap的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!