Site icon Java Guidance

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:

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:

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:

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:

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:

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:

Exit mobile version