1. Introduction

Java 8 provides a very useful Stream API that makes it easy to set up operations. Function map(Function > mapper) and flatMap(Function> mapper)

2. The map operations

A map operation reprocesses the elements of a stream to form a new stream. This is useful in development. Let’s say we have a set of students and we need to extract the ages of the students to analyze the age distribution curve of the students. Prior to Java 8 we would consume the age attribute in the element by creating a new collection and then iterating through the student collection. We have now fulfilled this requirement with a very simple streaming operation.

Schematic diagram:

Corresponding pseudocode:

List<Integer> ages= studentlist.stream ().map(Student::getAge).collect(Collectors. ToList ());Copy the code

3. FlatMap operation

The map operation should be easy to understand from the above example. So what does flatMap do? So let’s change the above example, if the unit is class, extract the ages of all students under all classes to analyze the curve of the age distribution of students. Is it still possible for us to use the above method?

 List<List<Student>> studentGroup= gradeList.stream().map(Grade::getStudents).collect(Collectors.toList());Copy the code

From the above operation, we can only get the set List> of the students in each class. We also need nested loops to get the student’s age data, which is very inconvenient. It would be much easier if we could return the set List of all students. That’s right! FlatMap does it!

List<Integer> ages = grades.stream(). FlatMap (grade -> grade.getStudents().stream()).map(Student::getAge).collect(Collectors.toList());Copy the code

As shown in the pseudocode above, we used flatMap to bring all the students together. The age is then extracted using the MAP operation. FlatMap differs from Map in that a Map only extracts attributes and puts them into a stream. FlatMap first extracts attributes and puts them into a smaller stream and then merges all the streams into a single stream. There is a sense of “every little bit adds up”.

Let me draw another picture to understand:

4. To summarize

Map operations and flatMap operations can be very easy to solve some data flow manipulation problems once you are familiar with them. As an extension, these two operations are not only available in Java 8 for Stream, but also for Optional.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn