Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

java - 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.

question from:https://stackoverflow.com/questions/65836898/how-to-map-a-stream-of-class-objects-into-a-stream-of-properties-of-said-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...