I am not really sure we’ve gotten the right idiom here yet. I’d like to slow down a bit before making an API decision.
What id suggest is capturing the proposed api and spec on list, and let’s let this sit and bake for a bit longer. My sense is that something better may well emerge if we do. Sent from my MacBook Wheel > On Oct 9, 2021, at 5:41 AM, Tagir F.Valeev <tval...@openjdk.java.net> wrote: > > On Sun, 3 Oct 2021 11:00:25 GMT, Tagir F. Valeev <tval...@openjdk.org> wrote: > >> Currently, when the stream holds a resource, it's necessary to wrap it with >> try-with-resources. This undermines the compact and fluent style of stream >> API calls. For example, if we want to get the `List` of files inside the >> directory and timely close the underlying filehandle, we should use >> something like this: >> >> >> List<Path> paths; >> try (Stream<Path> stream = Files.list(Path.of("/etc"))) { >> paths = stream.toList(); >> } >> // use paths >> >> >> I suggest to add a new default method to Stream interface named >> `consumeAndClose`, which allows performing terminal stream operation and >> closing the stream at the same time. It may look like this: >> >> >> default <R> R consumeAndClose(Function<? super Stream<T>, ? extends R> >> function) { >> Objects.requireNonNull(function); >> try(this) { >> return function.apply(this); >> } >> } >> >> >> Now, it will be possible to get the list of the files in the fluent manner: >> >> >> List<Path> list = >> Files.list(Path.of("/etc")).consumeAndClose(Stream::toList); > > CSR is [posted](https://bugs.openjdk.java.net/browse/JDK-8274994), please > review! > > ------------- > > PR: https://git.openjdk.java.net/jdk/pull/5796