1. preface
Java 8 Provides very useful Stream API , you can easily operate the collection. Today we will discuss two Stream intermediate operation map(Function<? super T, ? extends R> mapper)
and flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
2. map operation
map
The operation is to reprocess the elements in the flow to form a new flow. This is useful in development. For example, we have a set of students, and we need to extract the age of the students from it to analyze the age distribution curve of the students.
on Java 8 Previously, we would consume the age attribute in the element by creating a new collection and then iterating the student collection. Now we have completed this requirement through a very simple streaming operation.
Schematic diagram:
Corresponding pseudo-code:
<>=.().(::).(.());
3. flatMap operation
Through the above example,map
The operation should be very easy to understand. so flatMap
What does it do? In this way, let's change the above example. If it is based on classes, extract the ages of all students in all classes to analyze the age distribution curve of students. Is it still feasible for us to use the above method at this time?
<<>>=.().(::).(.());
Through the above operation, we can only get a set of students in each class List<List<Student>>
。We also need nested loops to obtain student age data, which is very inconvenient. If we could get back the entire student collection List<Students>
It's much more convenient. That's right!flatMap
It can be done!
<>=.().(->.().()).(::).(.());
As the pseudocode above shows, we use flatMap
Bring all students together. then use map
Operate to extract the age. flatMap
different from map
stands out with map
It just extracts attributes and puts them into the stream, while flatMap first extracts attributes and puts them into a smaller stream, and then combines all the streams into one stream. There is a feeling of "gathering sand to form a tower".
Draw another picture to deepen understanding:
4. summary
map
operation and flatMap
Once you are familiar with the operation, you can easily solve some data flow operation problems. To expand the knowledge, in fact, these two operations are not only present in Stream in Java 8, but actually Optional<T>
These two operations also exist in, and both have similar effects.
Comments0