java - 如何在迭代时向作为 HashMap 值的 ArrayList 添加内容?

标签 java performance data-structures hashmap big-o

我有一个 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/

相关文章:

java - RealmTransactions IDE 编辑器错误 : Expected Identifier

performance - 链接 LINQ 语句是否会导致多次迭代?

java - 在不同的 "context"中启动应用程序

java - 为什么 RouterFunctions.DefaultRouterFunction<T extends ServerResponse> 类中的谓词字段会获取 DefaultErrorWebExceptionHandler?

algorithm - Mergesort 对三个输入数组进行排序

performance - 获取所有 Neo4j 节点和关系的最快方法?

optimization - 用于搜索文件名并获取其路径的数据结构

algorithm - 修改深度优先搜索以在特定半径内工作

c++ - MergeSort 用于 double vector

java - DB2 重音不敏感大写 JPA