java - 在 Java 11 中使用流返回树形图
问题描述
我正在创建一个读取 .txt 文件并将树映射返回为 Tree 的函数
解决方案
你可以这样做,
Path path = Paths.get("path/to/file", "fileName.txt");
try (Stream<String> lines = Files.lines(path)) {
Map<Integer, Long> wordLengthCount = lines.map(l -> l.split(" ")).flatMap(Arrays::stream)
.filter(s -> !s.isEmpty())
.collect(Collectors.groupingBy(w -> w.length(), TreeMap::new, Collectors.counting()));
}
只需传入一个 mapFactory,一个供应商提供一个新的空 Map,结果将插入其中。您可以仅使用此处所示的构造函数引用来完成工作。另请注意,这是groupingBy
函数的重载。
正如下面在评论中提到的,这可以使用方法引用代替 lambda 进一步简化,
Map<Integer, Long> wordLengthCount = lines.map(l -> l.split(" ")).flatMap(Arrays::stream)
.filter(s -> !s.isEmpty())
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
回到您的上下文,我建议您将文件路径传递给该方法,它将返回您的Map
. 所以这就是它在实践中的样子。
public static Map<Integer, Long> wordCountByLength(String path) {
try (Stream<String> lines = Files.lines(Paths.get(path))) {
return lines.map(l -> l.split(" ")).flatMap(Arrays::stream).filter(s -> !s.isEmpty())
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
推荐阅读
- r - 查找具有 NA 值的 POSIXct 日期的最小值或最大值
- python - 启动单个jupyter笔记本时自动打开qtconsole?
- wordpress - 带有响应式图像的古腾堡自定义块
- php - 带有多个问题的 PHP 表单,每个问题都有多个选项,可根据选择输出文本响应
- observable - iOS RxSwift 是否从 .replay() 可连接的 observable 将完成事件传递给订阅者?
- php - 函数 App\Http\Controllers 0 传递的参数太少,预期正好 2 个”
- javascript - JavaScript 某些方法不起作用
- python - Moto mock lambda 发布 SNS
- javascript - 在初始化之前阻止调用的好习惯?
- javascript - 劫持表单提交,存储原始提交,添加处理,然后正常提交