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

Viewed 4404

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.

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)));
Related