12

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 Answer 1

12

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)));
Sign up to request clarification or add additional context in comments.

1 Comment

I would personally consider having split return a Stream<B> rather than a boolean, then you can just do original.flatMap(A::split).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.