Java Stream flatMap() Example
Ramesh Fadatare
Posted on December 9, 2021
The Java Stream flatMap() method is an intermediate operation.
The Stream.flatMap() function, as the name suggests, is the combination of a map and a flat operation. This means you first apply the map function and then flatten the result.
Java Stream flatMap() Example
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". It's basically a big List containing three more List. Flattening this means transforming it in a "one level" structure e.g. [ 1,2,3,4,5,6,7,8,9 ] i.e. just one list.
For example: In the below program, you can see that we have three lists that are merged into one by using a flatMap() function:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args)
{
List<Integer> evens = Arrays.asList(2, 4, 6);
List<Integer> odds = Arrays.asList(3, 5, 7);
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11);
List<Integer> numbers = Stream.of(evens, odds, primes)
.flatMap(list -> list.stream())
.collect(Collectors.toList());
System.out.println("flattend list: " + numbers);
}
}
Output:
flattend list: [2, 4, 6, 3, 5, 7, 2, 3, 5, 7, 11]
Related Java Stream API's Examples
- Java Stream filter() Example
- Java Stream map() Example
- Java Stream flatMap() Example
- Java Stream distinct() Example
- Java Stream limit() Example
- Java Stream peek() Example
- Java Stream anyMatch() Example
- Java Stream allMatch() Example
- Java Stream noneMatch() Example
- Java Stream collect() Example
- Java Stream count() Example
- Java Stream findAny() Example
- Java Stream findFirst() Example
- Java Stream forEach() Example
- Java Stream min() Example
- Java Stream max() Example
- Java Stream reduce() Example
- Java Stream toArray() Example
Posted on December 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024