Recursive stream

前端 未结 2 947
孤城傲影
孤城傲影 2020-12-08 10:57

I want to list all the files on my computer recursively using Java 8.

Java 8 provides a listFiles method that returns all the files and directories but

2条回答
  •  庸人自扰
    2020-12-08 11:33

    A new API to generate a stream of Paths by walking the filesystem recursively is Files.walk.

    If you really want to generate a stream recursively (not necessarily walking the file tree, but I'll continue using that as an example), it might be a bit more straightforward to accomplish the recursion using method references:

    class RecursiveStream {
        static Stream listFiles(Path path) {
            if (Files.isDirectory(path)) {
                try { return Files.list(path).flatMap(RecursiveStream::listFiles); }
                catch (Exception e) { return Stream.empty(); }
            } else {
                return Stream.of(path);
            }
        }
    
        public static void main(String[] args) {
            listFiles(Paths.get(".")).forEach(System.out::println);
        }
    }
    

    Method references turn out to be quite useful for adapting a named method that has the same "shape" (arguments and return type) as a functional interface to that functional interface. This also avoids the potential initialization circularity with storing a lambda in an instance or static variable and calling itself recursively.

提交回复
热议问题