让我解释一下我的问题场景。
我正在从文件中一次读取一行。然后我使用分隔符拆分该行,然后计算每个单词的频率并将其保存在 map 中。
代码片段:
Map<String, Integer> frequencyMap = new HashMap<>();
try {
fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = "";
while ((line = bufferedReader.readLine()) != null) {
frequencyMap = Arrays.stream(line.split(PHRASE_SEPARATOR))
.map(String::trim)
.collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
但是,当我阅读下一行时,它不会将键值对合并到已经存在的值中。如何确保在从文件中读取行时合并新的键值对。
最佳答案
由于您需要随时合并计数,因此您应该在单次运行中将文件作为字符串流读取、拆分和映射,如下所示:
Map<String,Integer> frequencyMap = Files.lines(Paths.get(fileName))
.map(line -> line.split(PHRASE_SEPARATOR))
.flatMap(Arrays::stream)
.map(String::trim)
.collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));
或者使用异常安全的方法:
Map<String,Integer> frequencyMap = null;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
frequencyMap = stream
.map(line -> line.split(PHRASE_SEPARATOR))
.flatMap(Arrays::stream)
.map(String::trim)
.collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));
} catch (IOException e) {
e.printStackTrace();
}
关于Java 8 - 如何将元素合并到 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43955434/