java - Why does Iterable<T> not provide stream() and parallelStream() methods? -
i wondering why iterable interface not provide stream() , parallelstream() methods. consider following class:
public class hand implements iterable<card> { private final list<card> list = new arraylist<>(); private final int capacity; //... @override public iterator<card> iterator() { return list.iterator(); } } it implementation of hand can have cards in hand while playing trading card game.
essentially wraps list<card>, ensures maximum capacity , offers other useful features. better implementing directly list<card>.
now, convienience thought nice implement iterable<card>, such can use enhanced for-loops if want loop on it. (my hand class provides get(int index) method, hence iterable<card> justified in opinion.)
the iterable interface provides following (left out javadoc):
public interface iterable<t> { iterator<t> iterator(); default void foreach(consumer<? super t> action) { objects.requirenonnull(action); (t t : this) { action.accept(t); } } default spliterator<t> spliterator() { return spliterators.spliteratorunknownsize(iterator(), 0); } } now can obtain stream with:
stream<hand> stream = streamsupport.stream(hand.spliterator(), false); so onto real question:
- why
iterable<t>not provide default methods implementstream(),parallelstream(), see nothing make impossible or unwanted?
a related question found following though: why stream<t> not implement iterable<t>?
oddly enough suggesting other way around.
this not omission; there detailed discussion on eg list in june of 2013.
the definitive discussion of expert group rooted @ this thread.
while seemed "obvious" (even expert group, initially) stream() seemed make sense on iterable, fact iterable general became problem, because obvious signature:
stream<t> stream() was not going want. things iterable<integer> rather have stream method return intstream, example. putting stream() method high in hierarchy make impossible. instead, made easy make stream iterable, providing spliterator() method. implementation of stream() in collection just:
default stream<e> stream() { return streamsupport.stream(spliterator(), false); } any client can stream want iterable with:
stream s = streamsupport.stream(iter.spliterator(), false); in end concluded adding stream() iterable mistake.
Comments
Post a Comment