Java 8 Stream : FlatMap example

Java8 FlatMap example

In this tutorial we are going to learn how to use flatmap.

1. Basic FlatMap Example:

List<List<String>> nestedList = Arrays.asList( Arrays.asList("apple", "banana"),
 Arrays.asList("orange", "grape", "kiwi") ); 

List<String> flatList = nestedList.stream() 
.flatMap(Collection::stream) 
.collect(Collectors.toList());

Explanation:

  • nestedList is a list of lists.
  • flatMap is used to flatten the nested structure into a single stream of strings.
  • The resulting flatList contains all individual strings from the nested lists.

2. FlatMap with Arrays:


String[] array1 = {"one", "two", "three"};

String[] array2 = {"four", "five", "six"};
List<String> result = Stream.of(array1, array2)
	.flatMap(Arrays::stream)
	.collect(Collectors.toList());

Explanation:

  • Stream.of creates a stream of arrays.
  • flatMap is used to flatten the arrays into a single stream.
  • The resulting result contains all individual strings from the arrays.

3. FlatMap with Optional:


List<String> words = Arrays.asList("hello", "world");

List<String> uniqueLetters = words.stream()
.map(word -> word.split(“”))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());

Explanation:

  • map is used to split each word into an array of letters.
  • flatMap then flattens these arrays into a single stream of letters.
  • distinct is used to get unique letters.
  • The resulting uniqueLetters list contains distinct letters from the original words.

4. FlatMap with Objects:


List<Person> people = Arrays.asList(
new Person("Alice", Arrays.asList("Java", "Python")),
new Person("Bob", Arrays.asList("C++", "JavaScript"))
);

List<String> distinctLanguages = people.stream()
.map(person -> person.getLanguages())
.flatMap(List::stream)
.distinct()
.collect(Collectors.toList());

Explanation:

  • map is used to extract the list of languages from each person.
  • flatMap flattens these lists into a single stream of languages.
  • distinct ensures that the resulting distinctLanguages list contains unique programming languages.

5. FlatMap with Stream of Integers:


List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(4, 5, 6);

List<Integer> result = Stream.of(numbers1, numbers2)
.flatMap(List::stream)
.collect(Collectors.toList());

Explanation:

  • flatMap is used to flatten two lists of integers into a single stream.
  • The resulting result list contains all integers from both lists.

6. FlatMap with Stream of Lists:


List<List<Integer>> listOfLists = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);

List<Integer> flatList = listOfLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());

Explanation:

  • flatMap is used to flatten a list of lists into a single stream of integers.
  • The resulting flatList contains all individual integers from the nested lists.