首页 > 解决方案 > 在 Java 11 中使用流返回树形图

问题描述

我正在创建一个读取 .txt 文件并将树映射返回为 Tree 的函数

标签: javastreambufferedreadertreemap

解决方案


你可以这样做,

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);
    }
}

推荐阅读