如何使用Java Streams API添加和更新Map条目完成词频统计?
实现代码
你不需要提前将流转换为数组,直接在流中串联所有处理逻辑即可,最终通过Collectors.toMap完成Map的构建和更新,和你原有手写循环的逻辑完全一致:
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; // 核心逻辑 Map<String, WordStatistics> wordToFrequencyMap = lines.stream() // 统一转小写,和原有逻辑对齐 .map(String::toLowerCase) // 按非字母字符分割为单词,扁平化处理为单词流 .flatMap(line -> Arrays.stream(line.split("[^a-zA-Z]+"))) // 过滤长度大于3的单词 .filter(word -> word.length() > 3) // 收集为目标Map结构 .collect(Collectors.toMap( // Map的key为单词本身 Function.identity(), // 首次出现的单词,构造WordStatistics实例,频次初始化为1 word -> new WordStatistics(word, 1), // 重复出现的单词,合并逻辑:累加已有实例的频次 (existingStats, newStats) -> { existingStats.setFreq(existingStats.getFreq() + newStats.getFreq()); return existingStats; } ));
排序实现
由于你已经为WordStatistics类实现了Comparable接口,直接对流中的WordStatistics实例调用sorted()方法即可按照你定义的规则排序:
List<WordStatistics> sortedList = wordToFrequencyMap.values().stream() .sorted() .collect(Collectors.toList());
内容的提问来源于stack exchange,提问作者Wtht.Nws
相关产品推荐
相关产品推荐

