I have a list of objects of class A
defined as below:
class A {
private Set<String> sOne;
private Set<String> sTwo;
// Constructor, getters and setters
}
Now I would like to create a stream which contains elements of both sOne
and stwo
. Is there a way to do it in Java 8?
concat() in Java. Stream. concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.
No. Java streams, once consumed, can not be reused by default. As Java docs say clearly, “A stream should be operated on (invoking an intermediate or terminal stream operation) only once.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
You can combine them using:
List<A> aList = ...;
Stream<String> stream = aList.stream()
.flatMap(a -> Stream.concat(
a.getsOne().stream(),
a.getsTwo().stream())
);
Stream.concat(sOne.stream(), sTwo.stream())
You should just be aware that this drops some characteristics IIRC in some cases.
An alternative to already mentioned Stream::concat
is the Stream::of
:
Stream.of(sOne.stream(), sTwo.stream())
.flatMap(Function.identity())
...
This requires to flatten the structure unless you wish to work with Stream<Stream<T>>
or a stream of any collection Stream<Collection<T>>
.
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