Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use one to many Mapping in java 8 stream?

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.

like image 216
FranXho Avatar asked Sep 13 '18 09:09

FranXho


People also ask

Can we use map stream in Java 8?

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.

Can we have multiple filter in stream Java?

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.

How do I combine two streams in Java?

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.


1 Answers

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)));
like image 106
Eran Avatar answered Sep 22 '22 03:09

Eran