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

add Iterable default method that returns Stream

    Details

    • Type: Enhancement
    • Status: Open
    • Priority: P4
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: tbd_major
    • 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
      }

        Issue Links

          Activity

          Hide
          jeff Jeff Dinkins added a comment -
          Is this an enhancement or a bug?
          Show
          jeff Jeff Dinkins added a comment - Is this an enhancement or a bug?
          Hide
          smarks Stuart Marks added a comment -
          Changed it to an enhancement. Also fix-version tbd_major since it would be an API change.
          Show
          smarks Stuart Marks added a comment - Changed it to an enhancement. Also fix-version tbd_major since it would be an API change.

            People

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

              Dates

              • Created:
                Updated: