在Java11中使用streams返回树映射
我正在创建一个函数,它读取一个.txt文件并将树映射返回为tree您可以这样做在Java11中使用streams返回树映射,java,stream,bufferedreader,treemap,Java,Stream,Bufferedreader,Treemap,我正在创建一个函数,它读取一个.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::strea
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()));
}
回到您的上下文,我建议您将文件路径传递给该方法,它将返回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);
}
}
公共静态映射wordCountByLength(字符串路径){
try(streamlines=Files.lines(path.get(path))){
返回lines.map(l->l.split(“”).flatMap(Arrays::stream).filter(s->!s.isEmpty())
.collect(Collectors.groupingBy(String::length,TreeMap::new,Collectors.counting());
}捕获(IOE异常){
抛出新的运行时异常(e);
}
}
您可以使用方法referenceString::length
作为groupingBy
的第一个参数。我用您的代码更新了我的问题,但仍然有错误。你能帮我吗?你面临的错误是什么。您必须将它们包括在问题中。您必须使用reader.lines()
因为您使用的是BufferedReader
我用它更新了它,并更新了我的代码和错误消息,我似乎有“错误:找不到符号”错误。
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);
}
}