Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8274412

Add a method to Stream API to consume and close the stream without using try-with-resources

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • core-libs
    • None

      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:

          /**
           * Applies given function to this stream, then closes the stream.
           * No further operation on the stream will be possible after that.
           *
           * @param function function to apply
           * @param <R> type of the function result
           * @return result of the function
           * @see #close()
           */
          default <R> R consumeAndClose(Function<? super Stream<T>, ? extends R> 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);

            tvaleev Tagir Valeev
            tvaleev Tagir Valeev
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: