The Stream API in Java processes the sequence of elements and performs the required operations on that sequence of elements. The Stream API is implemented using the java.util.stream package. This package comprises different classes, and methods that are implemented according to the requirement. The Stream flatMap() method is one of the methods that belong to Stream API in Java that can be used for mapping.
This article will demonstrate the working and implementation of the Stream flatMap() method in Java.
How to Use/Implement Stream flatMap() Function in Java?
The Stream flatMap() method in Java maps each element present on the stream to a new stream and also flattens the new stream. The mapper function passed in the flatMap() stream method returns a new stream by converting all the present streams into a single stream. The mapped stream is closed when the mapping process is finished.
The syntax along with the code implementation is depicted below:
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
- R shows the new stream element.
- Stream is the interface of Java.
- T is known as the type of stream element.
- The mapper function returns a new stream when mapped on each function.
Example 1: Basic Implementation of flatMap() Method in Java
The flatMap() method declared in the code example below returns the element without an array.
import java.util.*;
import java.util.stream.Stream;
//Declare the class
class FlatExample1{
// main() method of Java
public static void main(String[] args)
{
// List containing string is declared
List<String> list1 = Arrays.asList("Code","in","Java");
// Use Stream flatMap() function
list1.stream().flatMap(num -> Stream.of(num)).
forEach(System.out::println);
}
}
In the above code:
- The required package is imported.
- A class is declared as “FlatExample1” in Java.
- The object of the List is declared as “list1”.
- In the last step, the stream().flatMap() method flattens the declared Array.
Output
The below output shows that the input declared as (“Code”, “in”, “Java”) is printed simply without the specific list format using the flatMap() method.

Example 2: Conversion of a Nested List into a Single List
A list declared within a list is termed a nested list in Java. The example below shows that two lists are declared using the Arrays.asList() method. The flatMap() method returns the nested list as a single list.
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;
//Declare the class
class FlatExample2{
// main() method of Java
public static void main(String[] args)
{
//First list of Integers
List<Integer> l1 = Arrays.asList(11,17);
//Second list of Integers
List<Integer> l2 = Arrays.asList(21,24);
//Merging the two lists
List<List<Integer>> lists = Arrays.asList(l1,l2);
System.out.println("The Nested List is: " + lists);
//flatMap() method
List<Integer> allinteg = lists.stream()
.flatMap(a -> a.stream())
.collect(Collectors.toList());
//Output
System.out.println("The Combine List is : " + allinteg);
}
}
In the code above:
- The packages required for coding are declared.
- A class is declared as “FlatExample2” to implement the flatMap() method of Stream.
- The next step involves the declaration of two integer lists as “l1” and “l2” respectively.
- The flatMap() method in the last step flattens the two declared lists into a single list.
Output

Example 3: Calculate the Sum of Integers Using flatMap() Method
The flatMap() method in Java returns the sum of the integers using the mapToInt() method that returns an integer stream along with the sum() method to calculate the sum of the integers as depicted in the code below.
//Import the package
import java.util.*;
//Declare the class
class StreamExample3 {
//main() method
public static void main(String[] args)
{
List<List<Integer>> score = Arrays.asList(
Arrays.asList(11, 12),
Arrays.asList(24, 5));
int output = score.stream()
//flatMap() method
.flatMap(list -> list.stream()).mapToInt(Integer::intValue).sum();
System.out.println("The Sum of the numbers is: " + output);
}
}
In the above code:
- The class is declared as “StreamExample3”.
- In the main() method of Java, an integer list is declared as a “score”.
- The integer values are entered into the list using Arrays.asList() method in Java.
- In the next step, the stream() method returns the stream of the integers.
- The last part of the code block implements the flatMap() method along with the mapToInt() and the sum() methods to return the sum of list elements.
Output
The output below shows that the sum of the numbers declared in the list is printed as “52”.

Example 4: Extract a Specific Object Using flatMap() Method
The code below shows a way to extract a certain object from the declared list. In the first block, all the strings are initialized along with the return values.
//Import the required Packages
import java.util.*;
import java.util.stream.Collectors;
class Method {
//Declare two strings
private final String name;
private final Set<String> Designation;
//Declare a method with name and designation
public Method(String name) {
this.Designation = new HashSet<>();
this.name = name;
}
//function for the designation
public void add(String Designation) {
this.Designation.add(Designation);
}
//From the names acquire designations
public Set<String> getDesignation() {
return Designation;
}
}
In the Main class write the following code:
//The Main class
class Main {
//the main() method of Java
public static void main(String[] args) {
//Create a List of names and designations
List<Method> listOfnames = new ArrayList<>();
//Declare the 'name' and the 'designation'
Method John = new Method("John Smith");
John.add("Banker");
listOfnames.add(John);
//Declare the 'name' and the 'designation'
Method Lilly = new Method("Lilly Adam");
John.add("Teacher");
listOfnames.add(Lilly);
Set<String> Designation = listOfnames.stream()
.flatMap(name -> name.getDesignation().stream())
.collect(Collectors.toSet());
//Print the 'occupations' only
System.out.println("All the Designations are: ");
System.out.println(Designation);
}
}
In the above code block:
- The main() method of Java is declared.
- An object of the ArrayList is declared as “listOfnames”.
- The designations are added using the add() method of Java.
- In the last part of the code, the String data type is set to “Designation” along with the stream() and flatMap() methods to provide a flattened stream of elements.
- The flattened output is printed using the println() method of Java.
Output
The output below shows that the “Designations” are printed as “Banker” and “Teacher” respectively.

The examples discussed above have implemented the flatMap() method of the Stream class in detail since the map() and flatMap() methods look the same. Let us see the differences below to get clarity.
Difference Between map() and flatMap() Method in Java
The main difference between the map() and the flatMap() method in Java is that the map() method only maps a certain value and produces an output stream. On the other hand, the flatMap() method not only provides the stream of values but also flattens it. Another difference is that the map() method is referred to as one-to-one mapping whereas the flatMap() method is referred to as one-to-many mappings.
This sums up the implementation of the flatMap() method in Java.
Conclusion
The Stream flatMap() method not only maps the elements of a stream to a new stream but also flattens the stream and returns the output. It is used in a variety of applications like converting the nested list into a single list, calculating the sum of the numbers declared in the list, etc. This article has utilized the flatMap() method to print a stream of elements in Java.