我有一个 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
我需要 map 存储什么(忽略顺序):
{"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>
最佳答案
Java 8:
map.computeIfAbsent(line, k -> new ArrayList<>()).add(num);
Java 7:
ArrayList<Integer> values = map.get(line);
if (values == null) {
map.put(line, values = new ArrayList<>());
}
values.add(num);
关于java - 如何在迭代时向作为 HashMap 值的 ArrayList 添加内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887762/