Currently we have the following Stream.concat
in Java 8:
public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b);
I am surprised as to why there is no version taking a varargs of Stream<? extends T>
?
Currently I have code written like:
Stream<Integer> resultStream = Stream.concat(stream1, Stream.concat(stream2, Stream.of(element))) .filter(x -> x != 0) .filter(x -> x != 1) .filter(x -> x != 2);
If a varargs of this signature were available:
public static <T> Stream<T> concat(Stream<? extends T>... streams);
Then I could write it much more clearly as:
Stream<Integer> resultStream = Stream.concat( stream1, stream2, Stream.of(element) ) .filter(x -> x != 0) .filter(x -> x != 1) .filter(x -> x != 2);
Without all kinds of nested Stream.concat
calls.
Or are there other reasons why it is not provided?
I cannot think of such reasons, as we end up doing the job of a varargs call anyway now.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
With three streams we could write Stream. concat(Stream. concat(a, b), c) .
Streams are lazy because intermediate operations are not evaluated until terminal operation is invoked. Each intermediate operation creates a new stream, stores the provided operation/function and return the new stream. The pipeline accumulates these newly created streams.
There are a lot of benefits to using streams in Java, such as the ability to write functions at a more abstract level which can reduce code bugs, compact functions into fewer and more readable lines of code, and the ease they offer for parallelization.
Just flatMap
it:
public static void main(final String[] args) throws Exception { final Stream<String> stream1 = /*some stream*/ final Stream<String> stream2 = /*some stream*/ final Stream<String> stream3 = /*some stream*/ final Stream<String> stream4 = /*some stream*/ final Stream<String> stream5 = /*some stream*/ final Stream<String> stream = Stream.of(stream1, stream2, stream3, stream4, stream5).flatMap(Function.identity()); }
In your example:
Stream<Integer> resultStream = Stream.of(stream1, stream2, Stream.of(element)) .flatMap(identity()) .filter(x -> x != 0) .filter(x -> x != 1) .filter(x -> x != 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With