On Sun, Sep 26, 2021 at 6:13 PM Remi Forax <fo...@univ-mlv.fr> wrote: > > > List<Path> list = > > Files.list(Path.of("/etc")).map(Path::getFileName).consumeAndClose(Stream::toList); > > > > What do you think? > > This one does not work because if Path::getFileName fails with an exception, > close() will not be called.
Well, as Path::getFileName is not actually executed here, only linked, there are only a few chances when map(Path::getFileName) may fail. Probably StackOverflowError, OutOfMemoryError, or LinkageError. Probably not so important for properly functioning application. I mean, if something of these happens, leaking file descriptor would be a lesser problem. With best regards, Tagir Valeev. > What you are proposing here is equivalent to > try(var stream = Files.list(Path.of("/etc")).map(Path::getFileName)) { > stream.toList() > } > > instead of > try(var stream = Files.list(Path.of("/etc"))) { > stream..map(Path::getFileName).toList() > } > > regards, > Rémi > > > > > > > [1] > > https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StackWalker.html#walk(java.util.function.Function)