【发布时间】:2017-06-12 18:26:34
【问题描述】:
我有一个 HashMap,键的值是一个 ArrayList。当我逐行读取文件时,我需要添加到属于该特定键的 ArrayList 中。 该文件可能有 1 行或 100 万行,键名将是行(字符串),它的值将表示它在文件中出现的行号。
有人可以帮帮我吗?此外,这种快速的时间复杂性是否明智?如果不是,我该如何优化?
示例 test.txt:
Hello <== Line 0
Jello <== Line 1
Mello <== Line 2
Hello <== Line 3
Tello <== Line 4
Jello <== Line 5
Tello <== Line 6
Tello <== Line 7
我需要我的地图存储什么(忽略顺序):
{"Hello": [0, 3]}
{"Jello": [1, 5]}
{"Mello": [2]}
{"Tello": [4, 6, 7]}
我的代码是:
ArrayList<Integer> al = new ArrayList<Integer>();
Map<String, ArrayList<Integer>> hm = new HashMap<String, ArrayList<Integer>>();
int num = 0;
for (String line = file.readLine(); line != null; line = file.readLine()) {
map.put(line, al.add(num)); <== the issue is here, how to fix?
}
编译错误:
incompatible types: boolean cannot be converted to ArrayList<Integer>
【问题讨论】:
-
单独调用
al.add(num);,然后使用map.put(line, num);
标签: java performance data-structures hashmap big-o