Close

Java 8 Streams - Stream.flatMapToDouble Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

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

Method:

DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)

This intermediate operation returns an DoubleStream 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.


Examples


package com.logicbig.example.stream;

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
import java.util.stream.DoubleStream;

public class FlatMapToDoubleExample {

public static void main(String... args) {
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("1", "2"),
Arrays.asList("5", "6"),
Arrays.asList("3", "4")
);

DoubleStream dStream =
listOfLists.stream().flatMapToDouble(childList ->
childList.stream()
.mapToDouble(Double::new));
//let's peek and find average of the elements
OptionalDouble opt = dStream.peek(System.out::println)
.average();
if (opt.isPresent()) {
System.out.println("average: " + opt.getAsDouble());
}
}
}

Output

1.0
2.0
5.0
6.0
3.0
4.0
average: 3.5




package com.logicbig.example.stream;

import java.util.Arrays;
import java.util.OptionalDouble;
import java.util.stream.DoubleStream;

public class FlatMapToDoubleExample2 {

public static void main(String... args) {

String[][] arrayOfArrays = {{"1", "2"}, {"5", "6"}, {"3", "4"}};


DoubleStream dStream = Arrays.stream(arrayOfArrays)
.flatMapToDouble(childArray -> Arrays.stream(childArray)
.mapToDouble(Double::new));
OptionalDouble opt = dStream.peek(System.out::println)
.average();
if (opt.isPresent()) {
System.out.println("average: " + opt.getAsDouble());
}
}
}

Output

1.0
2.0
5.0
6.0
3.0
4.0
average: 3.5




See Also