Package com.infilos.utils.stream
Class Streams
- java.lang.Object
-
- com.infilos.utils.stream.Streams
-
public class Streams extends Object
-
-
Constructor Summary
Constructors Constructor Description Streams()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <T> Iterable<T>
iterateOnce(Stream<T> stream)
Iterates throughstream
only once.static <T,E extends Throwable>
voiditerateThrough(Stream<? extends T> stream, CheckedConsumer<? super T,E> consumer)
Iterates throughstream
sequentially and passes each element toconsumer
with exceptions propagated.
-
-
-
Method Detail
-
iterateOnce
public static <T> Iterable<T> iterateOnce(Stream<T> stream)
Iterates throughstream
only once. It's strongly recommended to avoid assigning the return value to a variable or passing it to any other method because the returnedIterable
'siterator()
method can only be called once. Instead, always use it together with a for-each loop, as in:
The above is equivalent to manually doing:for (Foo foo : iterateOnce(stream)) { ... if (...) continue; if (...) break; ... }
except using this API eliminates the need for a named variable that escapes the scope of the for-each loop. And code is more readable too.Iterable<Foo> foos = stream::iterator; for (Foo foo : foos) { ... }
Note that
iterateThrough()
should be preferred whenever possible due to the caveats mentioned above. This method is still useful when the loop body needs to use control flows such asbreak
orreturn
.
-
iterateThrough
public static <T,E extends Throwable> void iterateThrough(Stream<? extends T> stream, CheckedConsumer<? super T,E> consumer) throws E extends Throwable
Iterates throughstream
sequentially and passes each element toconsumer
with exceptions propagated. For example:void writeAll(Stream<?> stream, ObjectOutput out) throws IOException { iterateThrough(stream, out::writeObject); }
- Throws:
E extends Throwable
-
-