Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.

This is reflected in the arguments to each operation.

The map operation takes a Function, which is called for each value in the input stream and produces one result value, which is sent to the output stream.

The flatMap operation takes a function that conceptually wants to consume one value and produce an arbitrary number of values. However, in Java, it's cumbersome for a method to return an arbitrary number of values, since methods can return only zero or one value. One could imagine an API where the mapper function for flatMap takes a value and returns an array or a List of values, which are then sent to the output. Given that this is the streams library, a particularly apt way to represent an arbitrary number of return values is for the mapper function itself to return a stream! The values from the stream returned by the mapper are drained from the stream and are passed to the output stream. The "clumps" of values returned by each call to the mapper function are not distinguished at all in the output stream, thus the output is said to have been "flattened."

Typical use is for the mapper function of flatMap to return Stream.empty() if it wants to send zero values, or something like Stream.of(a, b, c) if it wants to return several values. But of course any stream can be returned.

Answer from Stuart Marks on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ stream-flatmap-java-examples
Stream flatMap() in Java with examples - GeeksforGeeks
Unlike map(), which performs one-to-one transformations, flatMap() can produce zero or more elements per input element, resulting in a flattened stream. ... import java.util.*; import java.util.stream.*; class GFG { public static void main(String[] ...
Published ย  January 23, 2026
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java streams โ€บ the difference between map() and flatmap()
The Difference Between map() and flatMap() | Baeldung
November 10, 2025 - Streams represent a sequence of objects whereas optionals are classes that represent a value that can be present or absent. We have the map() and flatMap() methods among other aggregate operations.
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ java 8 โ€บ java stream flatmap()
Java Stream flatMap() with Examples
August 26, 2023 - Learn to use Java Stream flatMap() method which is used to flatten a stream of collections to a stream of elements combined from all collections.
Top answer
1 of 16
1061

Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.

This is reflected in the arguments to each operation.

The map operation takes a Function, which is called for each value in the input stream and produces one result value, which is sent to the output stream.

The flatMap operation takes a function that conceptually wants to consume one value and produce an arbitrary number of values. However, in Java, it's cumbersome for a method to return an arbitrary number of values, since methods can return only zero or one value. One could imagine an API where the mapper function for flatMap takes a value and returns an array or a List of values, which are then sent to the output. Given that this is the streams library, a particularly apt way to represent an arbitrary number of return values is for the mapper function itself to return a stream! The values from the stream returned by the mapper are drained from the stream and are passed to the output stream. The "clumps" of values returned by each call to the mapper function are not distinguished at all in the output stream, thus the output is said to have been "flattened."

Typical use is for the mapper function of flatMap to return Stream.empty() if it wants to send zero values, or something like Stream.of(a, b, c) if it wants to return several values. But of course any stream can be returned.

2 of 16
853

Stream.flatMap, as it can be guessed by its name, is the combination of a map and a flat operation. That means that you first apply a function to your elements, and then flatten it. Stream.map only applies a function to the stream without flattening the stream.

To understand what flattening a stream consists in, consider a structure like [ [1,2,3],[4,5,6],[7,8,9] ] which has "two levels". Flattening this means transforming it in a "one level" structure : [ 1,2,3,4,5,6,7,8,9 ].

๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ stream โ€บ Stream.html
Stream (Java Platform SE 8 )
3 weeks ago - (If a mapped stream is null an empty stream is used, instead.) This is an intermediate operation. ... The flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the resulting elements into a new stream.
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ javas-flatmap-method-explained-3ab4cfc90e64
Javaโ€™s flatMap() Method Explained | Medium
October 23, 2024 - The flatMap() method is a great tool in Javaโ€™s Stream API that allows us to transform complex data structures into a flat, easily manipulated stream. It is commonly used when working with nested collections, where each element in a stream ...
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ java map โ€บ flatten a stream of maps to a single map in java
Flatten a Stream of Maps to a Single Map in Java | Baeldung
July 6, 2024 - public static <K, V> Map<K, V> mergeMapsUsingStream(List<Map<K, V>> listOfMaps) { return listOfMaps.stream() .flatMap(map -> map.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v2)); } Leveraging the functional programming paradigm, this stream-based approach provides an elegant and efficient solution while ensuring readability and maintainability. In this article, we delved into merging a stream of maps in Java and presented several methods to handle various scenarios, including merging maps containing duplicate keys and gracefully handling null values.
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java8 โ€บ java 8 flatmap example
Java 8 flatMap example - Mkyong.com
December 16, 2020 - In the above case, the Stream#filter will filter out the entire [a, b], but we want to filter out only the character a ยท 3.4 Below is the final version, and we combine the array first and follow by a filter later. In Java, to convert a 2d array into a 1d array, we can loop the 2d array and put all the elements into a new array; Or we can use the Java 8 flatMap to flatten the 2d array into a 1d array, or from Stream<String[]> to Stream<String>.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ difference-between-map-and-flatmap-in-java-stream
Difference Between map() And flatMap() In Java Stream - GeeksforGeeks
July 23, 2025 - Both of the functions map() and ... one input value, whereas flatMap() function produces an arbitrary number of values as output (ie zero or more than zero) for each input value....
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ java stream flatmap()
Java Stream flatMap() - Scaler Topics
May 4, 2023 - Java flatMap is a method that, when applied to a stream of values, maps each value to some required output value. The mapping or transformation of input to output takes place via a mapper, which is a Functional Interface.
๐ŸŒ
Wojciech Krzywiec
wkrzywiec.is-a.dev โ€บ wojciech krzywiec โ€บ java series flatmap
Java Series: Flatmap ยท Wojciech Krzywiec
December 12, 2021 - It brings us a lot of handy operations. flatMap() is one of them which gives us the possibility to merge multiple streams into one or flatten nested streams into one. Itโ€™s a very common pattern and is used many times in real projects. Code and tests from this post can be found in my repository: ...
Top answer
1 of 7
169

It doesn't make sense to flatMap a Stream that's already flat, like the Stream<Integer> you've shown in your question.

However, if you had a Stream<List<Integer>> then it would make sense and you could do this:

Stream<List<Integer>> integerListStream = Stream.of(
    Arrays.asList(1, 2), 
    Arrays.asList(3, 4), 
    Arrays.asList(5)
);

Stream<Integer> integerStream = integerListStream .flatMap(Collection::stream);
integerStream.forEach(System.out::println);

Which would print:

1
2
3
4
5

To do this pre-Java 8 you just need a loops:

List<List<Integer>> integerLists = Arrays.asList(
    Arrays.asList(1, 2), 
    Arrays.asList(3, 4), 
    Arrays.asList(5)
)

List<Integer> flattened = new ArrayList<>();

for (List<Integer> integerList : integerLists) {
    flattened.addAll(integerList);
}

for (Integer i : flattened) {
    System.out.println(i);
}
2 of 7
119

Made up example

Imagine that you want to create the following sequence: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 etc. (in other words: 1x1, 2x2, 3x3 etc.)

With flatMap it could look like:

IntStream sequence = IntStream.rangeClosed(1, 4)
                          .flatMap(i -> IntStream.iterate(i, identity()).limit(i));
sequence.forEach(System.out::println);

where:

  • IntStream.rangeClosed(1, 4) creates a stream of int from 1 to 4, inclusive
  • IntStream.iterate(i, identity()).limit(i) creates a stream of length i of int i - so applied to i = 4 it creates a stream: 4, 4, 4, 4
  • flatMap "flattens" the stream and "concatenates" it to the original stream

With Java < 8 you would need two nested loops:

List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
    for (int j = 0; j < i; j++) {
        list.add(i);
    }
}

Real world example

Let's say I have a List<TimeSeries> where each TimeSeries is essentially a Map<LocalDate, Double>. I want to get a list of all dates for which at least one of the time series has a value. flatMap to the rescue:

list.stream().parallel()
    .flatMap(ts -> ts.dates().stream()) // for each TS, stream dates and flatmap
    .distinct()                         // remove duplicates
    .sorted()                           // sort ascending
    .collect(toList());

Not only is it readable, but if you suddenly need to process 100k elements, simply adding parallel() will improve performance without you writing any concurrent code.

๐ŸŒ
Stack Abuse
stackabuse.com โ€บ java-8-streams-definitive-guide-to-flatmap
Java 8 Streams: Definitive Guide to flatMap()
May 17, 2023 - Each list contains the characters of one of the words in the original stream. This isn't a flattened list - it's two dimensional. If we were to flatten the list - it'd only be one list, containing all of the characters from all of the words sequentially. This is where flatMap() kicks in.
๐ŸŒ
Medium
rameshfadatare.medium.com โ€บ java-stream-flatmap-method-with-examples-6ca88ea446eb
Java Stream flatMap() Method with Examples | by Ramesh Fadatare | Medium
September 27, 2024 - To demonstrate the basic usage of flatMap(), we will create a Stream of lists and use flatMap() to flatten these lists into a single stream of elements. import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FlatMapExample { public static void main(String[] args) { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(4, 5, 6); List<Integer> list3 = Arrays.asList(7, 8, 9); Stream<List<Integer>> stream = Stream.of(list1, list2, list3); // Use flatMap() to flatten the lists into a single stream of elements Stream<Integer> flatMappedStream = stream.flatMap(List::stream); // Print the flattened elements flatMappedStream.forEach(System.out::println); } }
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2021 โ€บ 09 โ€บ java-8-stream-flatmap-example-list-of.html
Java 8 - Stream FlatMap Example - List of Lists to List
These examples are very common e.g. convert a list of Lists into a single big list and will not only be useful in understanding how flatmap works but also in your day-to-day programming. Btw, if you haven't started Java 8 yet, then you better first check these Java 8 Functional programming courses to get yourself familiar with essential Java 8 concepts like lambda expressions and Stream API.
๐ŸŒ
Medium
medium.com โ€บ @salvipriya97 โ€บ java-stream-api-when-to-use-map-and-flatmap-1dd19e37ff73
Java Stream API: When to use map() and flatMap() | by Priya Salvi | Medium
September 1, 2023 - The flatMap operation is used to transform each element in a stream into a stream of multiple elements.
๐ŸŒ
Java67
java67.com โ€บ 2016 โ€บ 03 โ€บ how-to-use-flatmap-in-java-8-stream.html
Java 8 Stream + FlatMap Example for Beginners | How to flat a list of list in Java? | Java67
The result would be [[3,7],[23... which will finally return [3,7,2,3,2,3,7]. In short, the flatMap() function is used to convert a Stream of Stream into a list of values....
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ java-stream-flatmap-method-examples-how-use-nikhil-gargatte
Java Stream flatMap Method: Examples and How to Use it
April 3, 2023 - The "flatMap" method is a powerful tool in the Java Stream API. It allows you to transform each element of a stream into a new stream of elements, and then combine all those streams into a single stream.
๐ŸŒ
Medium
medium.com โ€บ @reetesh043 โ€บ java-stream-map-vs-flatmap-60a10e666c75
Exploring the Differences: Java map vs. flatMap | by Reetesh Kumar | Medium
October 4, 2024 - The resulting stream contains the titles with the first letter capitalized which are collected into a new list. The flatMap() method transforms each element of a stream into zero or more elements of a new stream.