Java 8 – Stream flapMap method with examples

In this article, we will discuss Stream flatMap() method in details with examples using Collection and Arrays

1. Stream flatMap method :

  • This Stream method is an intermediate operation which reads stream and produces new stream after applying given function
  • Stream flatMap() method is stateless which means it is non-interfering with other elements in the stream
  • The difference between map() v/s flatMap() methods of Stream is that, map allows only transformation as per given function whereas flatMap performs both flattening as well as transformation
  • In short, flatmap() method converts Stream of Collection of elements to Stream of elements after flattening and transformation
  • For example, if we have List of Lists of String elements then applying flatMap produces List of String elements
  • Another intermediate operation can be applied to returned stream for example filter(), sorted(), distinct() methods can be applied after flatmap() operation, if required
  • Method signature :- <R> Stream<>R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

1.1 Flattening

  • Stream.flatMap() helps to convert Collection of Collection of elements into Collection of elements by flattening
  • That’s Collection<Collection<T>> to Collection<T>
  • For example, if you have List of List of String elements then we can merge into one single list of String elements
List of List of String elements - before flattening :-

[ ["Stephen", "Nathan"], ["Bob", "John", "Alice"], ["Ramesh", "Suresh", "Naresh", "Rajesh"] ]


After flattening :-

[ "Stephen", "Nathan", "Bob", "John", "Alice", "Ramesh", "Suresh", "Naresh", "Rajesh" ]
  • Similarly, if you have List of List of Integer elements then we can merge into one single list of Integer elements
List of List of Integer elements - before flattening :-

[ [1, 2, 3], [4, 5, 6], [7, 8, 9, 10] ]


After flattening :-

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

2. Stream flatMap method examples :

2.1 To convert List of Lists of String elements into List of String elements

  • Initially, there are 3 Lists each containing 3-4 String elements
  • We created another List of List which consists of all 3 List of String elements
  • Applied Stream’s flatmap() method to merge list of lists into single list
  • Note :- simple sysout to console before and after flattening to understand this example
  • Conversion :- List<List<String>> to List<String>
package net.bench.resources.stream.flatmap.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMapMethod {

	public static void main(String[] args) {

		// 1. create 1st List with 3 String elements
		List<String> firstList = Arrays.asList("Stephen", "Nathan", "Williams");

		// 2. create 1st List with 3 String elements
		List<String> secondList = Arrays.asList("Bob", "John", "Alice");

		// 3. create 1st List with 3 String elements
		List<String> thirdList = Arrays.asList("Ramesh", "Suresh", "Naresh", "Rajesh");

		// finally, create List of Lists
		List<List<String>> namesList = Arrays.asList(
				firstList, 
				secondList, 
				thirdList
				);

		System.out.println("1. Before flatMap and flattening :- \n\n"
				+ namesList);


		// merge List of List of String into single List
		List<String> resultingList = namesList
				.stream() // 1. get stream
				.flatMap(list -> list.stream()) // 2. intermediate operation
				.collect(Collectors.toList()); // 3. terminal operation

		System.out.println("\n\n2. Merging List of Lists into single List :- \n\n"
				+ resultingList);
	}
}

Output:

1. Before flatMap and flattening :- 

[[Stephen, Nathan, Williams], [Bob, John, Alice], [Ramesh, Suresh, Naresh, Rajesh]]


2. Merging List of Lists into single List :- 

[Stephen, Nathan, Williams, Bob, John, Alice, Ramesh, Suresh, Naresh, Rajesh]

2.2 To convert List of Lists of Integer elements into List of Integer elements

  • Initially, there are 3 Lists each containing 3-4 Integer elements
  • We created another List of List which consists of all 3 List of Integer elements
  • Applied Stream’s flatmap() method to merge list of lists into single list
  • Note :- simple sysout to console before and after flattening to understand this example
  • Conversion :- List<List<Integer>> to List<Integer>
package net.bench.resources.stream.flatmap.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMapMethodForInteger {

	public static void main(String[] args) {

		// 1. create 1st List with 3 Integer elements
		List<Integer> firstList = Arrays.asList(1, 2, 3);

		// 2. create 1st List with 3 Integer elements
		List<Integer> secondList = Arrays.asList(4, 5, 6);

		// 3. create 1st List with 3 Integer elements
		List<Integer> thirdList = Arrays.asList(7, 8, 9, 10);

		// finally, create List of Lists
		List<List<Integer>> numberList = Arrays.asList(
				firstList, 
				secondList, 
				thirdList
				);

		System.out.println("1. Before flatMap and flattening :- \n\n"
				+ numberList);


		// merge List of List of Integer into single List
		List<Integer> resultingList = numberList
				.stream() // 1. get stream
				.flatMap(list -> list.stream()) // 2. intermediate operation
				.collect(Collectors.toList()); // 3. terminal operation

		System.out.println("\n\n2. Merging List of Lists into single List :- \n\n"
				+ resultingList);
	}
}

Output:

1. Before flatMap and flattening :- 

[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]


2. Merging List of Lists into single List :- 

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2.3 To merge Arrays of Arrays into one List

  • We created 2-dimensional Arrays (i.e.; kind of Arrays of Arrays) which consists of all String elements
  • Applied Stream’s flatmap() method to merge 2-d Arrays into single list
  • Note :- simple sysout to console before and after flattening to understand this example
  • Conversion :- String[][] to List<String>
package net.bench.resources.stream.flatmap.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamFlatMapMethodForArrays {

	public static void main(String[] args) {

		// create 2-dimensional Arrays
		String[][] namesArray = new String[][] {
			{"Stephen", "Nathan", "Williams"}, 
			{"Bob", "John", "Alice"}, 
			{"Ramesh", "Suresh", "Naresh", "Rajesh"}
		};

		System.out.println("1. Before flatMap and flattening :- \n");

		for(int index=0; index < namesArray.length; index++) {
			System.out.println(Arrays.toString(namesArray[index]));
		}



		// merge Arrays of Arrays of String into single List
		List<String> resultingList = Arrays.stream(namesArray) // 1. get stream
				.flatMap(str -> Arrays.stream(str)) // 2. intermediate operation
				.collect(Collectors.toList()); // 3. terminal operation

		System.out.println("\n\n2. Merging Arrays of Arrays into single List :- \n\n"
				+ resultingList);



		System.out.println("\n\n3. Iterating 2-d Array using Java 8 forEach :- \n");

		// print to console using Java 8 forEach elegantly
		Stream.of(namesArray) // 1. get stream
		.flatMap(Stream::of) // 2. intermediate operation
		.forEach(name -> System.out.println(name)); // 3. terminal operation
	}
}

Output:

1. Before flatMap and flattening :- 

[Stephen, Nathan, Williams]
[Bob, John, Alice]
[Ramesh, Suresh, Naresh, Rajesh]


2. Merging Arrays of Arrays into single List :- 

[Stephen, Nathan, Williams, Bob, John, Alice, Ramesh, Suresh, Naresh, Rajesh]


3. Iterating 2-d Array using Java 8 forEach :- 

Stephen
Nathan
Williams
Bob
John
Alice
Ramesh
Suresh
Naresh
Rajesh

2.4 Flattening and removing duplicates

  • Initially, there are 3 Lists each containing 4 String elements with one duplicate in all 3 lists
  • We created another List of List which consists of all 3 List of String elements
  • Applied Stream’s flatmap() method to merge list of lists into single list and also applied another intermediate operation distinct() to remove duplicates
  • Note :- simple sysout to console before and after flattening to understand this example
  • Conversion :- List<List<String>> to List<String>
package net.bench.resources.stream.flatmap.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMapMethodAndRemoveDuplicates {

	public static void main(String[] args) {

		// 1. create 1st List with 3 String elements
		List<String> firstList = Arrays.asList("Stephen", "Nathan", "Williams", "Rajesh");

		// 2. create 1st List with 3 String elements
		List<String> secondList = Arrays.asList("Bob", "John", "Alice", "Rajesh");

		// 3. create 1st List with 3 String elements
		List<String> thirdList = Arrays.asList("Ramesh", "Suresh", "Naresh", "Rajesh");

		// finally, create List of Lists
		List<List<String>> namesList = Arrays.asList(
				firstList, 
				secondList, 
				thirdList
				);

		System.out.println("1. Before flatMap and flattening :- \n\n"
				+ namesList);


		// merge List of List of String into single List
		List<String> resultingList = namesList
				.stream() // 1. get stream
				.flatMap(list -> list.stream()) // 2.1 flatMap() intermediate operation
				.distinct() // 2.2 distinct() intermediate operation
				.collect(Collectors.toList()); // 3. terminal operation

		System.out.println("\n\n2. Merging List of Lists into single List"
				+ " and removing duplicates :- \n\n" + resultingList);
	}
}

Output:

1. Before flatMap and flattening :- 

[[Stephen, Nathan, Williams, Rajesh], [Bob, John, Alice, Rajesh], 
[Ramesh, Suresh, Naresh, Rajesh]]


2. Merging List of Lists into single List and removing duplicates :- 

[Stephen, Nathan, Williams, Rajesh, Bob, John, Alice, Ramesh, Suresh, Naresh]

2.5 Flattening and sorting

  • Initially, there are 3 Lists each containing 3-4 String elements
  • We created another List of List which consists of all 3 List of String elements
  • Applied Stream’s flatmap() method to merge list of lists into single list and also applied another intermediate operation sorted() to sort String elements inside flattened List
  • Note :- simple sysout to console before and after flattening to understand this example
  • Conversion :- List<List<String>> to List<String>
package net.bench.resources.stream.flatmap.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMapMethodAndSorting {

	public static void main(String[] args) {

		// 1. create 1st List with 3 String elements
		List<String> firstList = Arrays.asList("Stephen", "Nathan", "Williams");

		// 2. create 1st List with 3 String elements
		List<String> secondList = Arrays.asList("Bob", "John", "Alice");

		// 3. create 1st List with 3 String elements
		List<String> thirdList = Arrays.asList("Ramesh", "Suresh", "Naresh", "Rajesh");

		// finally, create List of Lists
		List<List<String>> namesList = Arrays.asList(
				firstList, 
				secondList, 
				thirdList
				);

		System.out.println("1. Before flatMap and flattening :- \n\n"
				+ namesList);



		// merge List of List of String into single List
		List<String> resultingList = namesList
				.stream() // 1. get stream
				.flatMap(list -> list.stream()) // 2.1 flatMap() intermediate operation
				.sorted(String::compareTo) // 2.2 sorted() intermediate operation
				.collect(Collectors.toList()); // 3. terminal operation

		System.out.println("\n\n2. Merging List of Lists into"
				+ " single List and sorting :- \n\n" + resultingList);
	}
}

Output:

1. Before flatMap and flattening :- 

[[Stephen, Nathan, Williams], [Bob, John, Alice], [Ramesh, Suresh, Naresh, Rajesh]]


2. Merging List of Lists into single List and sorting :- 

[Alice, Bob, John, Naresh, Nathan, Rajesh, Ramesh, Stephen, Suresh, Williams]

2.6 Flattening and filtering

  • Initially, there are 3 Lists each containing 3-4 String elements
  • We created another List of List which consists of all 3 List of String elements
  • Applied Stream’s flatmap() method to merge list of lists into single list and also applied another intermediate operation filter() to keep only those names which contains alphabet “a” and neglect all other names from flattened list
  • Note :- simple sysout to console before and after flattening to understand this example
  • Conversion :- List<List<String>> to List<String>
package net.bench.resources.stream.flatmap.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMapMethodAndFiltering {

	public static void main(String[] args) {

		// 1. create 1st List with 3 String elements
		List<String> firstList = Arrays.asList("Stephen", "Nathan", "Williams");

		// 2. create 1st List with 3 String elements
		List<String> secondList = Arrays.asList("Bob", "John", "Alice");

		// 3. create 1st List with 3 String elements
		List<String> thirdList = Arrays.asList("Ramesh", "Suresh", "Naresh", "Rajesh");

		// finally, create List of Lists
		List<List<String>> namesList = Arrays.asList(
				firstList, 
				secondList, 
				thirdList
				);

		System.out.println("1. Before flatMap and flattening :- \n\n"
				+ namesList);



		// merge List of List of String into single List
		List<String> resultingList = namesList
				.stream() // 1. get stream
				.flatMap(list -> list.stream()) // 2.1 flatMap() intermediate operation
				.filter(str -> str.contains("a")) // 2.2 filter() intermediate operation
				.collect(Collectors.toList()); // 3. terminal operation

		System.out.println("\n\n2. Merging List of Lists into single List and filtering :- \n\n"
				+ resultingList);
	}
}

Output:

1. Before flatMap and flattening :- 

[[Stephen, Nathan, Williams], [Bob, John, Alice], [Ramesh, Suresh, Naresh, Rajesh]]


2. Merging List of Lists into single List and filtering :- 

[Nathan, Williams, Ramesh, Naresh, Rajesh]

2.7 Flattening and removing duplicates and then finally sorting

  • Initially, there are 3 Lists each containing 3-4 String elements
  • We created another List of List which consists of all 3 List of String elements
  • Applied Stream’s flatmap() method to merge list of lists into single list and also applied another intermediate operation distinct() to remove duplicates and then finally sorting distinct elements using Stream’s sorted() method
  • Note :- simple sysout to console before and after flattening to understand this example
  • Conversion :- List<List<String>> to List<String>
package net.bench.resources.stream.flatmap.example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMapAndRemoveDuplicatesAndSorting {

	public static void main(String[] args) {

		// 1. create 1st List with 3 String elements
		List<String> firstList = Arrays.asList("Stephen", "Nathan", "Williams", "Rajesh");

		// 2. create 1st List with 3 String elements
		List<String> secondList = Arrays.asList("Bob", "John", "Alice", "Rajesh");

		// 3. create 1st List with 3 String elements
		List<String> thirdList = Arrays.asList("Ramesh", "Suresh", "Naresh", "Rajesh");

		// finally, create List of Lists
		List<List<String>> namesList = Arrays.asList(
				firstList, 
				secondList, 
				thirdList
				);

		System.out.println("1. Before flatMap and flattening :- \n\n"
				+ namesList);


		// merge List of List of String into single List
		List<String> resultingList = namesList
				.stream() // 1. get stream
				.flatMap(list -> list.stream()) // 2.1 flatMap() intermediate operation
				.distinct() // 2.2 distinct() intermediate operation
				.sorted(String::compareTo) // 2.3 sorted() intermediate operation
				.collect(Collectors.toList()); // 3. terminal operation

		System.out.println("\n\n2. Merging List of Lists into single List"
				+ " and removing duplicates :- \n\n" + resultingList);
	}
}

Output:

1. Before flatMap and flattening :- 

[[Stephen, Nathan, Williams, Rajesh], [Bob, John, Alice, Rajesh], 
[Ramesh, Suresh, Naresh, Rajesh]]


2. Merging List of Lists into single List and removing duplicates :- 

[Alice, Bob, John, Naresh, Nathan, Rajesh, Ramesh, Stephen, Suresh, Williams]

References:

Happy Coding !!
Happy Learning !!

Java 8 - Difference between map() and flatMap() in Stream API
Java 8 - Stream map method with examples