During Devoxx Belgium, after the talk of Brian and Jose Paumard, there was an
interesting discussion among some Java8 early adopters about the fact that in
the API there no xommon way to get a Stream for anything that is conceptually a
collection.
I propose to introduce the following new methods on Stream:
/**
* Returns a sequential|Stream| with the iterable as its source.
*
* @param T the type of stream elements.
* @param iterable the iterable used as source of the stream.
* @return a sequential stream.
*/
public static <T> Stream<T> from(Iterable<T> iterable) {
return StreamSupport.stream(iterable.spliterator(), false);
}
/**
* Returns a sequential|Stream| with the collection as its source.
*
* @param T the type of stream elements.
* @param collection the collection used as source of the stream.
* @return a sequential stream.
*/
public static <T> Stream<T> from(Collection<T> collection) {
return collection.stream();
}
/**
* Returns a sequential|Stream| with the array as its source.
*
* @param T the type of stream elements.
* @param array the array used as source of the stream.
* @return a sequential stream.
*/
public static <T> Stream<T> from(T[] array) {
return Stream.of(array);
}
These methods are like the of() methods but of() overloads deal with values
while from() deal with collections.
This also re-introduce a way to get a stream from an unknown Iterable that was
removed from Iterable
because we want implementation of Iterable to be able to return Stream of
primitives.
I know that this is late in the game, but I think that given these methods just delegates to existing methods,
it will be better to introduce them in Java8 than in Java9.
cheers,
Rémi