Core Java

Java 8 Stream – flatMap & Optional Example

Hello. In this tutorial, we will talk and understand the most commonly used Java 8 Stream APIs: the flatMap method and the Optional class.

1. Introduction

Before diving deep into the practice stuff let us understand the flatMap method and Optional class in java programming.

1.1 flatMap() method

This method is used to convert a stream of collections to a stream of objects. It is an intermediate method and returns a stream as the output value. The mapper function used performs the transformation and is a stateless function which only returns the stream of new values. Each mapped stream is closed after its contents have been placed into a new stream. Represented by the syntax:

map() method

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

1.2 Optional class

The Optional class in java programming is used to handle the null pointer exception. This class provides methods that are used to check the presence of value. Here in this tutorial, we will understand its usage with the help of the flatMap method.

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 flatmap() implementation

Create a java file in the com.jcg.assignment package and add the following content to it. The file will consist of a method performing the flattening operation on three lists with the help of the flatMap() method.

Java8FlatmapExample.java

package com.jcg.assignment;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// Stream.flatMap() function is used to get a single list containing all elements from a list of lists.

public class Java8FlatmapExample {

    private static void flatMapImplementation() {
        final List<String> teamChelsea = Arrays.asList("Timo Werner", "Mason Mount", "Kai Havertz");
        final List<String> teamPortugal = Arrays.asList("Cristiano Ronaldo", "Pepe", "André Silva");
        final List<String> teamManchester = Arrays.asList("Jadon Sancho", "Paul Pogba");

        final List<String> flatMapList = Stream.of(teamChelsea, teamPortugal, teamManchester)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());

        System.out.println("----- List of all players using Java8 -----");
        flatMapList.forEach(System.out::println);
    }

    public static void main(String[] args) {
        flatMapImplementation();
    }
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

----- List of all players using Java8 -----
Timo Werner
Mason Mount
Kai Havertz
Cristiano Ronaldo
Pepe
André Silva
Jadon Sancho
Paul Pogba

2.2 Optional class implementation

Create a java file in the com.jcg.assignment package and add the following content to it. The file will consist of two methods showing the Optional class and flatMap() method implementation.

OptionalFlatmapExample.java

package com.jcg.assignment;

import java.util.Optional;

public class OptionalFlatmapExample {

    private static void optionalFlatmapExample() {
        final Optional<String> stringOptional = Optional.of("Welcome to javacodegeeks");

        final Optional<String> result = Optional.of(stringOptional)     // Represents two level nested optional instance.
                .flatMap(val -> val.map(String::new));
        System.out.println("Output = " + result.get());
    }

    private static void emptyOptionalExample() {
        final Optional<String> emptyOptional = Optional.empty();

        final Optional<String> result = Optional.of(emptyOptional)      // Represents two level nested optional instance.
                .flatMap(val -> Optional.of("No value found."));
        System.out.println("Output = " + result.get());
    }

    public static void main(String[] args) {
        optionalFlatmapExample();
        emptyOptionalExample();
    }
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

Output = Welcome to javacodegeeks

Output = No value found.

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned the implementation of flatMap method and Optional class in Java8 Stream API. You can download the source code from the Downloads section.

4. Download the Eclipse Project

This was a tutorial on learning and implementing the flatMap method and the Optional class introduced in Java8 Stream API.

Download
You can download the full source code of this example here: Java 8 Stream – flatMap & Optional Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button