Core Java

Java 8 flatMap Example

Hello readers, in this tutorial, we will learn about Java8 Streams API flatMap() method and in which structure it can be used.

1. Introduction

A flatMap() method is a Java8 programming operation which takes a single function as an argument. This function accepts the T parameter as an input argument and returns a stream of R 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’s flatMap() method is a merger of two operations i.e. a Map operation and a Flattening 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’s map() method as we have an irregular structure. To solve this problem, developers can use the flatMap() 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

In java.util.stream.Stream<T>, the flatMap() method is defined as,

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

Where,

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

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

  • The Stream’s map() method produces or returns a single result value, which is sent to the Output stream
  • The Stream’s flatMap() method produces or returns a Stream of elements
  • The flatMap() method is a combination of Map and Flattening operation
  • The map() method is only used for modification while the flatMap() method is used for both flattening and modification
  • The flatMap() 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 API flatMap() 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 to File -> 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 a pom.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 the src/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)

Once the package is created in the application, we will need to create the implementation class to demonstrate the flatMap() 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 of Stream.flatMap() method in Java8 programming. In this example, we have a Stream of the list of String elements and by using the flatMap() 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 World
		List<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 the Stream.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 the flatMap() method in Java8.

Download
You can download the full source code of this example here: Java8FlatmapEx

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button