Somasundaram Sekar Somasundaram Sekar - 1 month ago 16
Java Question

Java 8: Flattening Stream<Stream>

I want do a Cartesian product on Quarter on a year between the years specified

Year(2105, 2016) should return Quarter(2015, Q1), Quarter(2015, Q2)... Quarter(2016, Q4)

The enum representing Quarter would be

public enum Quarters {
Q1, Q2, Q3, Q4
}


and the code I'm trying to come up with is stuck as below

IntStream.rangeClosed(this.getYear(), to.getYear()).boxed().map(
i -> Arrays.stream(Quarters.values()).map(
q -> new Quarter(i, q)
)

);


The above code return
Stream<Stream<Quarter>>
which I would require to be flattened to
Stream<Quarter>
any help is appreciated.

Answer

You can use flatMap to flatten your Stream<Stream<Quarter>> to a Stream<Quarter> :

IntStream.rangeClosed(this.getYear(), to.getYear()).boxed().map(
                        i -> Arrays.stream(Quarters.values()).map(
                                q -> new Quarter(i, q)
                        ).flatMap(Function.identity ())

);

The body of the flatMap would simply be an identity function.

Or, as Alexis suggested, you can directly use flatMap instead of map :

IntStream.rangeClosed(this.getYear(), to.getYear())
         .boxed()
         .flatMap(i -> Arrays.stream(Quarters.values())
                             .map(q -> new Quarter(i, q))
         );
Comments