Skip to content
Advertisement

How to map a stream of class objects into a stream of properties of said class?

I have a class that has 3 properties, all with the same data type, let’s say:

Class Test {
    int i;
    int j;
    int k;
}

Then, I have a stream containing test classes (assume all the properties are notnull random integers):

Stream<Test> originalStream = Stream.of(test1,test2,test3);

How can I convert (or map?) that stream to a stream, made up by integers of the class. Printing now the stream would look like this (printing is not the point, I just used it to illustrate how it should be structured):

{test1,test2,test3}

But what I want is for it to look like this:

{test1.i, test1.j, test1.k, test2.i, test2.j, test2.k, test3.i, test3.j, test3.k}

I know I probably didn’t use the correct terminology (instance, object etc.), but I hope my question is clear.

Advertisement

Answer

Java streams have a powerful method called flatMap(), which lets you map each element in the stream to another stream, and then returns all of the streams joined together. So it does exactly what you’re asking for, all in one method. In your particular case, you are using integers, so they even have a specific method for this case called flatMapToInt(), which allows you to use a stream of primitive integer values, rather than their boxed equivalents. Here’s a simple one-liner using your given example:

IntStream expandedStream = originalStream.flatMapToInt((t) -> IntStream.of(t.i, t.j, t.k));

This just turns each element (named t here) into an IntStream containing t.i, t.j, and t.k. When the method returns, it returns a stream that is made up of all of those 3 element streams combined.

Advertisement