Stream<String> 仅输入来自 Files.lines() 的最后一行
Stream<String> Only inputting the last line from Files.lines()
在我的代码中我有
Files.lines(Paths.get(fileName), Charset.forName("Cp1252"))
.filter(k -> k != "")
.forEach(m -> hashmap.put(LocalDateTime.MIN, m));
从名为“info
”(fileName
) 的文件中读取行。
1
2
3
4
5
(blank line)
但是,当扫描 HashMap 时,它告诉我使用此代码仅插入了最后一行:
int x = 0;
for (HashMap.Entry<LocalDateTime, String> s : hashmap.entrySet()) {
x++;
System.out.println(hashmap.size() + ": " + x + ": " + s.getValue());
}
只打印一次 1: 1: 5
。
问题是您的代码片段将所有行放在同一个键下进入 HashMap
。此代码
.forEach(m -> hashmap.put(LocalDateTime.MIN, m));
从文件中取出每一行,并将其放在等于 LocalDateTime.MIN
的键处。由于 HashMap
不能包含多个相同的键,最后一项是 forEach
完成后映射中唯一剩余的项。
要解决此问题,请选择不同的容器,例如列表,或使用不同的策略将键分配给您从文件中读取的行。
在我的代码中我有
Files.lines(Paths.get(fileName), Charset.forName("Cp1252"))
.filter(k -> k != "")
.forEach(m -> hashmap.put(LocalDateTime.MIN, m));
从名为“info
”(fileName
) 的文件中读取行。
1
2
3
4
5
(blank line)
但是,当扫描 HashMap 时,它告诉我使用此代码仅插入了最后一行:
int x = 0;
for (HashMap.Entry<LocalDateTime, String> s : hashmap.entrySet()) {
x++;
System.out.println(hashmap.size() + ": " + x + ": " + s.getValue());
}
只打印一次 1: 1: 5
。
问题是您的代码片段将所有行放在同一个键下进入 HashMap
。此代码
.forEach(m -> hashmap.put(LocalDateTime.MIN, m));
从文件中取出每一行,并将其放在等于 LocalDateTime.MIN
的键处。由于 HashMap
不能包含多个相同的键,最后一项是 forEach
完成后映射中唯一剩余的项。
要解决此问题,请选择不同的容器,例如列表,或使用不同的策略将键分配给您从文件中读取的行。