Core Java

Java 8 flatMap Example

Photo of YatinYatinFebruary 1st, 2018Last Updated: February 25th, 2019
0 798 4 minutes read

Hello readers, in this tutorial, we will learn about Java8Streams APIflatMap() method and in which structure it can be used.

1. Introduction

AflatMap() method is a Java8 programming operation which takes a single function as an argument. This function accepts theT parameter as an input argument and returns a stream ofR parameter. When this function is applied to each element of this stream, it constructs a stream of new values. All the generated elements of these new streams are then again copied to a recent stream, which will then act as a return value of this method.

 
To add further, Stream’sflatMap() method is a merger of two operations i.e. aMap operation and aFlattening operation. To understand this better, let’s take an example of multiple lists having String elements such as{a, b},{c, d, e} etc. Now, if developers want to retrieve all the elements in a single concatenation, they can’t use the Stream’smap() method as we have an irregular structure. To solve this problem, developers can use theflatMap() method to flatten it into a structure like{a, b, c, d, e, .. }. The below diagram explains this.

Fig. 1: Java8 flatMap
Fig. 1: Java8 flatMap

1.1 Method Syntax

Injava.util.stream.Stream<T>, theflatMap() method is defined as,

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

Where,

  • TheflatMap() method takes the instance ofFunction<T,R>, namedmapper as an input argument. This converts the current typeT elements to another stream of typeR
  • This method returns an output stream of typeR elements which is literally aflattened stream obtained when the mapper is applied on the input stream’s elements of typeT
  • For “x” elements in an input stream of typeT, developers first get the “x” streams of typeR and later these “x” streams are then flattened into a single stream of typeR. Thus, aStream<Stream<R>> becomesStream<R>

1.2 Stream.map() vs. Stream.flatMap()

  • The Stream’smap() method produces or returns a single result value, which is sent to the Output stream
  • The Stream’sflatMap() method produces or returns a Stream of elements
  • TheflatMap() method is a combination ofMap andFlattening operation
  • Themap() method is only used formodification while theflatMap() method is used for bothflattening andmodification
  • TheflatMap() method replaces a value with a Stream and join all Streams together

Now, open up the Eclipse Ide and I will explain further about the usage of Stream’s APIflatMap() method in Java8 programming.

2. Java8 flatMap Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 2: Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go toFile -> New -> Maven Project.

Fig. 3: Create Maven Project
Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 4: Project Details
Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default:0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and apom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>Java8FlatmapEx</groupId><artifactId>Java8FlatmapEx</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging></project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in explaining this tutorial.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on thesrc/main/java folder,New -> Package.

Fig. 6: Java Package Creation
Fig. 6: Java Package Creation

A new pop window will open where we will enter the package name as:com.jcg.java.

Fig. 7: Java Package Name (com.jcg.java)
Fig. 7: Java Package Name (com.jcg.java)
Want to be a Java 8 Ninja ?
Subscribe to our newsletter and download the Java 8 FeaturesUltimateGuideright now!
In order to get you up to speed with the major Java 8 release, we have compiled a kick-ass guide with all the new features and goodies! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

Once the package is created in the application, we will need to create the implementation class to demonstrate theflatMap() method used. Right-click on the newly created package:New -> Class.

Fig. 8: Java Class Creation
Fig. 8: Java Class Creation

A new pop window will open and enter the file name as:FlatmapDemo. The implementation class will be created inside the package:com.jcg.java.

Fig. 9: Java Class (FlatmapDemo.java)
Fig. 9: Java Class (FlatmapDemo.java)

3.1.1 Example of flatMap Method

Here is the complete Java program to demonstrate the use ofStream.flatMap() method in Java8 programming. In this example, we have a Stream of the list of String elements and by using theflatMap() method we convert this into a Stream of String elements.

FlatmapDemo.java

package com.jcg.java;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;/**  * This java program demonstrates the use of 'flatMap()' method in Java8 programming.  * The 'flatMap()' function is used to convert a Stream of list of values to a Stream of values and this process is called "Flattening of Streams".  * * @author Batra, Yatin **/public class FlatmapDemo {public static void main(String[] args) {List<String> houseGryffindor = Arrays.asList("Albus", "Harry", "Ron", "Hermione");List<String> houseHufflepuff = Arrays.asList("Bridget", "Cedric", "Nymphadora");List<String> houseRavenclaw = Arrays.asList("Luna", "Garrick", "Filius");List<String> houseSlytherin = Arrays.asList("Severus", "Tom", "Phineas");List<List<String>> hogwarts = new ArrayList<List<String>>(); hogwarts.add(houseGryffindor);hogwarts.add(houseHufflepuff);hogwarts.add(houseRavenclaw);hogwarts.add(houseSlytherin);// Printing All Hogwarts Houses In Pre-Java8 WorldList<String> listOfAllHouses = new ArrayList<String>();for(List<String> house : hogwarts) {for(String hName : house) {listOfAllHouses.add(hName);}}System.out.println("<!---------------Hogwarts Houses---------------!>");System.out.println(listOfAllHouses);System.out.println();// Now let's Achieve This By Using 'flatMap()' Method In Java8 List<String> flatMapList = hogwarts.stream().flatMap(hList -> hList.stream()).collect(Collectors.toList()); System.out.println("<!---------------Hogwarts Houses Using Java8---------------!>"); System.out.println(flatMapList);}}

4. Run the Application

To run the application, developers need to right-click on the class,Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 10: Run Application
Fig. 10: Run Application

5. Project Demo

The above code shows the following logs as output.

# Logs for 'FlatmapDemo' #=====================<!---------------Hogwarts Houses---------------!>[Albus, Harry, Ron, Hermione, Bridget, Cedric, Nymphadora, Luna, Garrick, Filius, Severus, Tom, Phineas]<!---------------Hogwarts Houses Using Java8---------------!>[Albus, Harry, Ron, Hermione, Bridget, Cedric, Nymphadora, Luna, Garrick, Filius, Severus, Tom, Phineas]

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we had an in-depth look at theStream.flatMap() method with an example. I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of theflatMap() method in Java8.

Download
You can download the full source code of this example here:Java8FlatmapEx
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinFebruary 1st, 2018Last Updated: February 25th, 2019
0 798 4 minutes read
Photo of Yatin

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

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.