src/share/classes/java/lang/Iterable.java

Print this page
rev 7626 : 8015320: Pull spliterator() up from Collection to Iterable
Reviewed-by:
Contributed-by: brian.goetz@oracle.com

@@ -24,10 +24,12 @@
  */
 package java.lang;
 
 import java.util.Iterator;
 import java.util.Objects;
+import java.util.Spliterator;
+import java.util.Spliterators;
 import java.util.function.Consumer;
 
 /**
  * Implementing this interface allows an object to be the target of
  * the "for-each loop" statement. See

@@ -70,7 +72,28 @@
         Objects.requireNonNull(action);
         for (T t : this) {
             action.accept(t);
         }
     }
+
+    /**
+     * Creates a {@link Spliterator} over the elements described by this
+     * {@code Iterable}.
+     *
+     * @implNote
+     * <p>The default implementation should usually be overridden.  The
+     * spliterator returned by the default implementation has poor splitting
+     * characteristics, is unsized, does not report any other spliterator
+     * characteristics, and is <em><a href="Spliterator.html#binding">early-binding</a></em>.
+     * Implementing classes can nearly always provide a better implementation.
+     * The returned spliterator inherits the <em>fail-fast</em> properties of the
+     * collection's iterator.
+     *
+     * @return a {@code Spliterator} over the elements described by this
+     * {@code Iterable}.
+     * @since 1.8
+     */
+    default Spliterator<T> spliterator() {
+        return Spliterators.spliteratorUnknownSize(iterator(), 0);
+    }
 }