How to flatten a stream using flatMap() method in Java

Hey, Coders! In this tutorial, we are going to learn about flatten a stream using the flatMap() method in Java.

map(): It transforms each stream element into a single element of a new stream.

flatMap(): It transforms each stream element into a stream of multiple elements.

Flattening: It is the process of converting two or more lists into a single list by merging them. It contains all the elements of all the lists.

flatten a stream using flatMap() method in Java

Example 1:

Before flattening: [[1,2,3], [4,5,6], [7,8,9]]
After flattening: [1,2,3,4,5,6,7,8,9]

Example 2:

Before flattening: [[“A”,”B”,”C”], [“D”,”E”,”F”], [“G”,”H”,”I”]]
After flattening: [“A”,”B”,”C”,”D”,”E”,”F”,”G”,”H”,”I”]

Syntax:
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

  • R  is a parameter that represents the new stream type.
  • mapper is the function that maps each element of the stream to a new stream.
  • T is the type of the stream element.
  • Stream is an interface.

Code 1:  flatMap() function with provided mapping integers.

import java.util.*; 
import java.util.stream.Collectors; 
class CodeSpeedy 
{
    public static void main(String[] args) 
    {
        List<Integer> a = Arrays.asList(1,2,3);
        List<Integer> b = Arrays.asList(4,5,6);
        List<Integer> c = Arrays.asList(7,8,9); 
        List<List<Integer>> ListofInts = Arrays.asList(a, b, c); 
        System.out.println("Before flattening: " + ListofInts); 
        List<Integer> listInt  = ListofInts.stream() .flatMap(list -> list.stream()) .collect(Collectors.toList()); 
        System.out.println("After flattening: " + listInt); 
    } 
}

Output:

Before flattening: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
After flattening: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Code 2: flatMap() function with provided mapping characters.

import java.util.*;
import java.util.stream.Collectors;
class CodeSpeedy {
    public static void main(String[] args) {
        List<String> a = Arrays.asList("A","B","C");
        List<String> b = Arrays.asList("D","E","F");
        List<String> c = Arrays.asList("G","H","I");
        List<List<String>> ListOfAlphabets = Arrays.asList(a,b,c);
        System.out.println("Before flattening: " + ListOfAlphabets);
        List<String> listAlphabets = ListOfAlphabets.stream().flatMap(alphabetList -> alphabetList.stream()).distinct().collect(Collectors.toList());
        System.out.println("After flattening: " + listAlphabets);
    }
}

Output:


Before flattening: [[A, B, C], [D, E, F], [G, H, I]]
After flattening: [A, B, C, D, E, F, G, H, I]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top