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

add Iterator.stream() default method

    Details

    • Type: Enhancement
    • Status: Open
    • Priority: P4
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: tbd
    • Component/s: core-libs
    • Labels:

      Description

      I should not have to rummage around in StreamSupport to connect my iterable thing up to the Stream API. StreamSupport is not easily discoverable, whereas a postfix method call (".stream()" or ".stream().parallel()") is easy to discover.

      The static factory method in StreamSupport does not work well with a fluent API. We often obtain iterables as results from method call chains, and of course streams themselves are highly fluent. But sticking the StreamSupport static call in the middle breaks the chain and makes it harder to read.

      So:

      interface Iterable<T> {
          /**
           * Creates a {@link Stream} over the elements described by this
           * {@code Iterable}.
           * The created
      ...
           * @since 1.10
           */
          default Stream<T> stream() {
              return StreamSupport.stream(this.spliterator(), false);
          }

          /**
           * Creates a {@link Spliterator} over the elements described by this
           * {@code Iterable}.
      ...
           * @since 1.8
           */
          default Spliterator<T> spliterator() {
              return Spliterators.spliteratorUnknownSize(iterator(), 0);
          }
      }

      If there are name conflicts on "stream" for this very common type, I suggest "iterateStream", "spliteratorStream", or the like instead of "stream". I also suggest that default methods be allowed to collide with regular methods in such cases, where the return type differs.

      class TroutFishingInAmerica implements Iterable {
        String stream() { return "the old fishing hole"; } // default method should not disturb this
      }

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                smarks Stuart Marks
                Reporter:
                jrose John Rose
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated: