Return 使用 Java 11 中的流的树图
Return a Tree Map using streams in Java 11
我正在创建一个读取 .txt 文件和 returns 树映射为 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,供应商提供一个新的空地图,结果将插入其中。您只需使用此处所示的构造函数引用即可完成工作。另请注意,这是 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()));
回到您的上下文,我建议您将文件路径传递给该方法,它将 return 您 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);
}
}
我正在创建一个读取 .txt 文件和 returns 树映射为 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,供应商提供一个新的空地图,结果将插入其中。您只需使用此处所示的构造函数引用即可完成工作。另请注意,这是 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()));
回到您的上下文,我建议您将文件路径传递给该方法,它将 return 您 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);
}
}