问题描述
我有一百万行 .txt 格式的数据.格式非常简单.对于每一行:
用户 1,值 1用户2,价值2用户 3,价值 3用户 1,值 4...你知道我的意思.对于每个用户,它可能出现多次,或者只出现一次(你永远不知道).我需要找出每个用户的所有值.因为用户可能随机出现,所以我使用 Hashmap 来做.即:HashMap(key: String, value: ArrayList).但是要向arrayList添加数据,我必须不断地使用HashMap get(key)来获取arrayList,给它添加值,然后把它放回HashMap.我觉得效率不是很高.有人知道更好的方法吗?
您无需将 ArrayList 重新添加回您的 Map.如果 ArrayList 已经存在,那么只需将您的值添加到它.
改进的实现可能如下所示:
Map>map = new HashMap>();
在处理每一行时:
String user = 行中的用户字段字符串值 = 行中的值字段集合<字符串>值 = map.get(user);如果(值==空){值 = 新的 ArrayList<String>();map.put(用户,值)}values.add(value);
2014 年 4 月跟进 - 我在 2009 年写了原始答案,当时我对 Google Guava 的了解有限.鉴于 Google Guava 所做的一切,我现在建议使用它的 Multimap
而不是重新发明它.
Multimap值 = 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][值2][值3]
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 ...
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?
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>>();
while processing each line:
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);
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"));
Outputs:
[value4, value1]
[value2]
[value3]
这篇关于创建arraylist哈希图的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!