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);
}
Answer from Nick Holt on Stack Overflow
🌐
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.
🌐
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
Discussions

Java 8 Streams FlatMap method example - Stack Overflow
I have been checking the upcoming Java update, namely: Java 8 or JDK 8. Yes, I am impatient, there's a lot of new stuff, but, there is something I don't understand, some simple code: final Stream More on stackoverflow.com
🌐 stackoverflow.com
What's the difference between map() and flatMap ...
The type signature kinda tells the whole story. map :: Stream T -> (T -> R) -> Stream R, flatMap :: Stream T -> (T -> Stream R) -> Stream R. ... fwiw, those type signatures don't even look like Java. More on stackoverflow.com
🌐 stackoverflow.com
Is it possible to understand what flatMap does?
The way I started to finally get it is in the context of network requests. Say you have a request that fetches a URL, and then you want to get whatever is at that second URL. You’d use flatMap on the value you get from the first publisher to create the second publisher, then continue working with the value from that second publisher in your overall pipeline. Map transforms a value into another value. FlatMap transforms a value into a publisher of other values. It’s similar to array if you think of the Combine context as a publisher within a publisher and you want to flatten the whole pipeline into a simple stream of values. More on reddit.com
🌐 r/iOSProgramming
16
17
August 30, 2021
Alternative uses for `flatMap`
The basic example to use flatMap in case of lists would be something like this: import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { System.out.println("Hello World"); Arrays.asList("myA", "myB", "myC") .stream() .flatMap(x -> getNewStream()) .forEach(ell -> System.out.println(ell)); } private static Stream getNewStream() { String[] arr = { "A", "B", "C" }; return Arrays.stream(arr); } } Usually, .flatMap() is a shorthard for .map()-ing, and then .flatten()-ing. The function itself is not necessary, but it's a useful shorthand. Basically, you're replacing the "contained" value into a "container" value with different type-parameter. And then flattening both containers into a single one - depending on the type of container there will be different semantics. More on reddit.com
🌐 r/learnjava
5
2
June 29, 2021
🌐
Websparrow
websparrow.org › home › java stream map() vs flatmap() method
Java Stream map() vs flatMap() Method - Websparrow
May 27, 2023 - This function is applied to each element of the original stream, and the resulting streams are then concatenated into a single stream. Let’s consider an example to understand the usage of flatMap(): ... package org.websparrow; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class JavaStreamFlatMapTest { public static void main(String[] args) { List<List<Integer>> numbers = Arrays.asList( Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9) ); List<Integer> flattenedNumbers = numbers.stream() .flatMap(Collection::stream) .collect(Collectors.toList()); System.out.println(flattenedNumbers); } }
🌐
Baeldung
baeldung.com › home › java › java streams › the difference between map() and flatmap()
The Difference Between map() and flatMap() | Baeldung
November 10, 2025 - The flatMap() method first flattens the input Stream of Streams to a Stream of Strings (for more about flattening, see this article). Thereafter, it works similarly to the map() method.
🌐
Medium
medium.com › @kavya1234 › understanding-map-flatmap-and-reduce-in-java-8-stream-api-d67818ab509d
Understanding Map, flatMap and reduce in Java 8 Stream API | by Kavya | Medium
June 15, 2024 - Java 8 introduced the Stream API, which is a powerful tool for processing sequences of elements. Among the most commonly used operations are map, flatMap, and reduce.
🌐
Stackademic
blog.stackademic.com › the-flatmap-trick-99-of-java-developers-dont-know-and-it-honestly-changes-everything-9e7dd06dc290
The FlatMap Trick 99% of Java Developers Don’t Know — And It Honestly Changes Everything | by Shanu Reddy | Stackademic
December 4, 2025 - If you’ve worked with Java Streams for a while, you already know the usual moves: map, filter, sorted, maybe a collect when you're feeling confident. But there’s one Stream operation that quietly holds more power than we realize — flatMap.
Find elsewhere
🌐
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.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › stream › Stream.html
Stream (Java SE 21 & JDK 21)
January 20, 2026 - The default implementation invokes flatMapToLong on this stream, passing a function that behaves as follows. First, it calls the mapper function with a LongConsumer that accumulates replacement elements into a newly created internal buffer. When the mapper function returns, it creates a LongStream from the internal buffer.
🌐
Vanderbilt
dre.vanderbilt.edu › ~schmidt › cs253 › 2023-PDFs › 7.2.8-overcoming-limitations-with-flatMap.pdf pdf
Java Parallel Streams Internals: Overcoming
Limitations with flatMap() in Parallel Streams · • The Java flatMap() implementation · oddly forces sequential processing · <R> Stream<R> flatMap · (Function<? super P_OUT, ? extends Stream<? extends R>> mapper) { ... public void accept(P_OUT u) { try(Stream<? extends R> result ·
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.

🌐
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.
🌐
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>.
🌐
Javacodehouse
javacodehouse.com › blog › java-streams-map-vs-flatmap
Java Streams - Map vs FlatMap
December 23, 2023 - In summary, the key difference is in the nature of the transformation. map is for one-to-one transformations. flatMap is for one-to-many transformations, flattening the result into a single 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.
🌐
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 ...
🌐
ZetCode
zetcode.com › java › stream-flatmap
Java Stream flatMap - Flattening Streams in Java
Java Stream flatMap tutorial provides a comprehensive guide on using the flatMap method to transform and flatten nested data structures in Java streams. Learn how to optimize functional programming with flatMap, apply stream transformations, and enhance data processing efficiency.
🌐
Java Guides
javaguides.net › 2024 › 07 › java-stream-flatmap-method.html
Java Stream flatMap() Method
July 3, 2024 - This method does not throw any exceptions. The flatMap() method allows you to take each element of the original stream, transform it into a new stream, and then combine these multiple streams into a single stream.
🌐
Wojciech Krzywiec
wkrzywiec.is-a.dev › wojciech krzywiec › java series flatmap
Java Series: Flatmap · Wojciech Krzywiec
December 12, 2021 - Java 8 was a great step forward toward modern programing language. One of the key features added in this release was Java streams. It provides lots of convenient operations for data processing. One of them is a flatMap() used very widely to unwrap and merge multiple collections into one.
🌐
C# Corner
c-sharpcorner.com › article › understanding-flatmap-in-java
Understanding flatMap in Java
July 23, 2024 - The FlatMap is an intermediate operation in Java Streams that maps each element to a stream and then flattens the resulting streams into a single stream. It's like a combination of map and flatten operations.
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 ].