In map
function of Stream
we can convert one object to another, so we can covert one Stream
that contains 3 elements of type A to another Stream
of 3 elements of type B.
How do I convert 3 elements of type A
Stream
to 6 or more elements of type B
Stream
depending on condition?
In term of code.
We can do
Stream<B> converted = original.map( a -> new B(a) );
But how can we do like following ?
Steam<B> converted = original.map( a -> {
if(a.split()){
return [ new B(a), new B(a) ];
}else return new B(a);
});
I was not able to find and understand how to do that. Thank ahead.
Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.
The Stream API allows chaining multiple filters. We can leverage this to satisfy the complex filtering criteria described. Besides, we can use the not Predicate if we want to negate conditions.
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.
You use flatMap
in order to map each element of the original Stream
to a Stream
of elements of some type.
Steam<B> converted = original.flatMap( a -> {
if(a.split()){
return Stream.of(new B(a), new B(a));
} else {
return Stream.of(new B(a));
}
});
or
Steam<B> converted = original.flatMap(a -> a.split() ?
Stream.of(new B(a), new B(a)) :
Stream.of(new B(a)));
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