flatMap() Method in Java 87 May 2025 | 10 min read In Java 8 Streams, the flatMap() method applies an operation as a mapper function and provides a stream of element values. It means that in each iteration of each element, the map() method creates a separate new stream. By using the flattening mechanism, it merges all streams into a single resultant stream. In short, it is used to convert a Stream of streams into a list of values. ![]() The flatMap() method works in the following way:
Syntax: The method takes a function as an argument. It accepts T as a parameter and returns a stream of R. R: It is a type parameter that represents the element type of the new stream. mapper: It is a parameter that is a non-interfering, stateless function to apply to each element. It produces a stream of new values. The mapper has the following properties: Non-Interfering: The property signifies that the mapper does not alter the elements within the input Stream. Instead, it generates a distinct result for each element in the input Stream. Stateless: In contrast to stateful behavior, where actions rely on previously processed items, stateless behavior processes each element independently. Consequently, for a given input, the mapper consistently produces the same output without considering previous elements. In short, we can say that the flatMap() method helps in converting Stream<Stream<T>> to Stream<T>. It performs flattening (flat or flatten) and mapping (map) simultaneously. The Stream.flatMap() method combines both the operations, i.e., flat and map. Return Value of Java Stream.flatMap() MethodThe Java flatMap() method returns a new Stream of type R. This is evident from the method signature discussed in the syntax. The method, flatMap(), suggests two distinct operations:
Let's understand the meaning of flattening. What is flattening?Flattening refers to the process of converting a nested data structure (such as a collection of collections) into a single, flat structure. It is often used in programming when we want to simplify nested data like lists or arrays into a single list or array. In Java, it can be achieved using streams, where we can convert a list of lists into a single list. The flatMap() method is commonly used in Java to perform flattening. For example, converting a list of lists of integers into a single list of integers, eliminating any nested structure, results in a one-dimensional collection. Flattening ExampleConsider the following lists of lists: Before Flattening: [[1, 2, 3, 4], [7, 8, 9, 0], [5, 6], [12, 18, 19, 20, 17], [22]] After Flattening: [1, 2, 3, 4, 7, 8, 9, 0, 5, 6, 12, 18, 19, 20, 17, 22] Example of the flatMap() MethodWe can use a flatMap() method on a stream with the mapper function List::stream. On executing the stream terminal operation, each element of flatMap() provides a separate stream. In the final phase, the flatMap() method transforms all the streams into a new stream. In the above stream, we observe that it does not contain duplicate values. Let's create a Java program and use the flatMap() method. ExampleCompile and RunOutput: List Before Applying mapping and Flattening: [Printer, Mouse, Keyboard, Motherboard, Scanner, Projector, Lighten, Pen Drive, Charger, WIFI Adapter, Cooling Fan, CPU Cabinet, WebCam, USB Light, Microphone] List After Applying Mapping and Flattening Operation: [Printer, Mouse, Keyboard, Motherboard, Scanner, Projector, Light Pen, Pen Drive, Charger, WIFI Adapter, Cooling Fan, CPU Cabinet, WebCam, USB Light, Microphone] Use Cases of Stream.flatMap() MethodFlattening a Nested List to a ListFlattening a nested list into a single list is a common operation when dealing with complex data structures. In Java 8, it can be efficiently achieved by using the flatMap() method. ExampleCompile and RunOutput: [1, 2, 3, 4, 5, 6, 7, 8, 9] Flattening a Nested Array to a ListFlattening a nested array into a single list is another common operation similar to flattening a nested list. In Java 8, it can also be efficiently achieved by using the flatMap() method, but with a slight difference in handling arrays. ExampleCompile and RunOutput: [1, 2, 3, 4, 5, 6, 7, 8, 9] Java Stream.flatMap() with Primitive TypesIn Java 8, the Stream API provides specialized streams for primitive types, such as IntStream, LongStream, and DoubleStream. When working with these primitive streams, you might need to use the flatMap() method to flatten nested structures of primitive types. ExampleCompile and RunOutput: [1, 2, 3, 4, 5, 6, 7, 8, 9] Word Count of a Text FileCounting the number of words in a text file is a fundamental task in text processing and analysis. This operation can be useful in various applications such as text analytics, content management, and data preprocessing. In Java, we can perform word count efficiently using the Stream API. The Stream API provides a modern, functional approach to processing sequences of elements, making it well-suited for tasks like reading and manipulating text files. ExampleCompile and RunOutput: Word count: 37 Demo.txt
Now, we have understood both the methods of the Stream class since we can easily point out the key differences between them. Differences Between Stream.flatMap() and Stream.map() MethodThe following table describes the key differences between Stream.flatMap() and Stream.map(). ![]()
Important Points to Remember
Java Stream.flatMap() Method MCQs1. Which of the following mappings is performed by the flatMap() method?
Answer: 2) Explanation: It performs One-to-Many mapping that involves mapping one value to either zero or more values. For example, one-to-many mapping occurs when you flatten a single stream of strings to zero or more string values. 2. Which operations are performed by the flatMap() method?
Answer: 3) Explanation: It performs flattening (flat or flatten) and mapping (map) simultaneously. The Stream.flatMap() method combines both the operations, i.e., flat and map. 3. What is a mapper in the flatMap() method?
Answer: 3) Explanation: It is a parameter that is a non-interfering, stateless function to apply to each element. It produces a stream of new values. 4. Which of the following is true about flatMap() method?
Answer: 3) Explanation: The flatMap() method applies an operation as a mapper function and provides a stream of element values. It means that in each iteration of each element, the map() method creates a separate new stream. By using the flattening mechanism, it merges all streams into a single resultant stream. 5. Which of the following is a valid use case for the flatMap() method?
Answer: 1) Explanation: Use cases for the flatMap() method are:
Next TopicMoser-de-bruijn-sequence-in-java |
? In Java, the ArrayList is a widely used data structure that allows dynamic resizing of elements. When it comes to displaying the contents of an ArrayList, the default behavior is to print the elements enclosed within square brackets. However, there are scenarios where you might want...
5 min read
? With the help of Java's dynamic SQL queries, we can create and execute SQL statements instantly, giving your database interactions flexibility and adaptability. In this section, we will discuss the process of writing dynamic SQL queries in Java in this article, which includes comprehensive code examples...
5 min read
In the world of Java programming, data structures play a crucial role in storing and manipulating data efficiently. Two commonly used data structures for this purpose are vectors and arrays. While both are used to store collections of elements, they have distinct differences that make them...
13 min read
In Java, default parameters are a powerful feature that allows developers to define default values for method parameters. This can be useful when a method has a large number of parameters, and some of them are not always required. Default parameters were introduced in Java 8 and...
4 min read
Java operator's precedence refers to the set of rules that dictate the order of evaluation of the different constituents of a given expression. In programming, the use of bitwise operators like XOR (^) and OR (|) is important. So, it is essential to learn how these...
4 min read
The java.util package contains the LongSummaryStatistics class. When dealing with a stream of long integers, it accepts a collection of Long objects and can be advantageous. It keeps track of how many values it has processed, how much they have added up to, and other...
4 min read
Java Database Connectivity (JDBC) is an Application Programming Interface (API), from Sun microsystem that is used by the Java application to communicate with the relational databases from different vendors. JDBC and database drivers work in tandem to access spreadsheets and databases. defines the components of...
4 min read
The Two Sum - Pairs with Zero Sum is another algorithmic problem referred to as a problem of identifying pairs of integers in an array that sum up to zero. This problem is quite common among coding interviews and competitive programming since it requires not only...
5 min read
The java.nio.FloatBuffer Class's clear() function is used to clear this buffer. The mark has been eliminated using the above method, which sets the position and limit to zero and capacity, respectively. When a specific order of channel read or put operations is required, this procedure...
4 min read
We can develop more adaptable and reusable interfaces in Java since an interface can include a generic type parameter. Classes, methods, and various other interfaces which may operate on a wide range of distinct data types can be defined using generic interfaces. Declaring an arbitrary interface follows...
5 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India