Close

Java 8 Streams - Stream.flatMap Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

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

This intermediate operation returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null an empty stream is used, instead.


Examples


package com.logicbig.example.stream;

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

public class FlatMapExample {

public static void main(String... args) {
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("one", "two"),
Arrays.asList("five", "six"),
Arrays.asList("three", "four")
);

List<String> result = listOfLists.stream()
.flatMap(childList -> childList.stream())
.collect(Collectors.toList());
System.out.println(result);
}
}

Output

[one, two, five, six, three, four]




A parallel stream example.

package com.logicbig.example.stream;

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

public class FlatMapExample2 {

public static void main(String... args) {
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("one", "two"),
Arrays.asList("five", "six"),
Arrays.asList("three", "four")
);
List<String> result = listOfLists.stream()
.parallel()
.flatMap(childList -> childList.stream())
.collect(Collectors.toList());
System.out.println(result);

}
}

Output

[one, two, five, six, three, four]




package com.logicbig.example.stream;

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

public class FlatMapExample4 {

public static void main(String... args) {
String[][] arrayOfStringArrays = {{"one", "two"}, {"five", "six"}, {"three", "four"}};
List<String> result = Arrays.stream(arrayOfStringArrays)
.flatMap(childArray -> Arrays.stream(childArray))
.collect(Collectors.toList());
System.out.println(result);
}


}

Output

[one, two, five, six, three, four]




See Also