Sunday, April 18, 2021

Java Stream flatMap(). HOW-TO

Source:
https://howtodoinjava.com/java8/stream-flatmap-example/#:~:text=flatMap()%20is%20an%20intermediate,mapping%20function%20to%20each%20element

flatMap() - sample of flattening:

Flattening example 1
Before flattening   : [[1, 2, 3], [4, 5], [6, 7, 8]]
After flattening    : [1, 2, 3, 4, 5, 6, 7, 8]


Flattening example 2
Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8);
Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +")));


Similar flatMap() Methods
IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)



No comments: