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:
nestedListis a list of lists.flatMapis used to flatten the nested structure into a single stream of strings.- The resulting
flatListcontains 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.ofcreates a stream of arrays.flatMapis used to flatten the arrays into a single stream.- The resulting
resultcontains 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:
mapis used to split each word into an array of letters.flatMapthen flattens these arrays into a single stream of letters.distinctis used to get unique letters.- The resulting
uniqueLetterslist 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:
mapis used to extract the list of languages from each person.flatMapflattens these lists into a single stream of languages.distinctensures that the resultingdistinctLanguageslist 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:
flatMapis used to flatten two lists of integers into a single stream.- The resulting
resultlist 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:
flatMapis used to flatten a list of lists into a single stream of integers.- The resulting
flatListcontains all individual integers from the nested lists.
