DEV Community

Ramesh Fadatare
Ramesh Fadatare

Posted on • Originally published at sourcecodeexamples.net

Java Stream flatMap() Example

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

flattend list: [2, 4, 6, 3, 5, 7, 2, 3, 5, 7, 11]
Enter fullscreen mode Exit fullscreen mode

Related Java Stream API's Examples

  1. Java Stream filter() Example
  2. Java Stream map() Example
  3. Java Stream flatMap() Example
  4. Java Stream distinct() Example
  5. Java Stream limit() Example
  6. Java Stream peek() Example
  7. Java Stream anyMatch() Example
  8. Java Stream allMatch() Example
  9. Java Stream noneMatch() Example
  10. Java Stream collect() Example
  11. Java Stream count() Example
  12. Java Stream findAny() Example
  13. Java Stream findFirst() Example
  14. Java Stream forEach() Example
  15. Java Stream min() Example
  16. Java Stream max() Example
  17. Java Stream reduce() Example
  18. Java Stream toArray() Example

Top comments (0)