Part 6 – map vs flatMap in Java 8

7

The Difference Between map() and flatMap()

What have we learned so far

1. Functional Interface And Default Methods In Java 8 –
PART 1 : FUNCTIONAL INTERFACE AND DEFAULT METHODS IN JAVA 8

2. Lambda Expression in Java 8
PART 2 – LAMBDA EXPRESSION IN JAVA 8

3. Method Reference in Java 8
PART 3 – METHOD REFERENCE IN JAVA 8

4. Optional in Java 8
PART 4 – OPTIONAL IN JAVA 8

5. filter(), findAny() in Java 8
PART 5 – FILTER(), FINDANY() IN JAVA 8

map() in Java 8

<R> Stream<R> map(Function<? super T, ? extends R> mapper);
a stream consisting of the results of applying the given function to the elements of this stream. Map takes an input which describes how the value needs to be transformed into.
Suppose we want to get the age of the Student whose name is Saurabh, till now we have only retrieved the complete object from the stream but how do we do this ?
We can use map() to transform the Student Stream into the age stream as below.

int age = students.stream()
    .filter(student -> SAURABH.equals(student.getName()))
    .map(Student::getAge)
    .findAny()
    .orElse(0);
System.out.printf("*** Age of %s is %dn",SAURABH, age);

Now lets try to get all the names of the students with the help of collect()

Set<String> names = students.stream()
       .map(Student::getName) // this will convert the Student Stream into String Stream by 
        // applying the getName()
              .collect(Collectors.toSet());  
System.out.printf("*** All the names from the list is %sn",names);

What is the use of flatMap() in Java 8?

map vs flatMap

Suppose we want to get all the courses available in students list then we can write the code as below:

Set<String> courses = students.stream()
         .map(Student::getCourses)
         .collect(Collectors.toSet());

Here we will get a compilation error as below
Type mismatch: cannot convert from Set<String[]> to Set<String>
To resolve this issue we use flatMap()

flatMap() in Java 8

It returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
flatMap will transform the stream of stream into simple stream. In below example we are using the flatMap to convert the Array of Stream into the String stream.

Set<String> courses = students.stream()
         .map(Student::getCourses)
         .flatMap(Arrays::stream)
         .collect(Collectors.toSet());

Source Code
Download source code of Java 8 features from below git repository :
java-8-features

Java 8 Features Tutorial

https://www.onlyfullstack.com/java-8-features-tutorial/

Lets go to our next tutorial where we will discuss below points :

Stream.peek() in Java 8
In this tutorial we will understand below topics – How Stream.peek() method is different from other methods?
 – What is the use of peek() method in Java 8?
PART 7 – STREAM.PEEK() IN JAVA 8