Java Stream flatMapToDouble Example

1. Introduction

In this quick tutorial, we will see how to use the flatMapToDouble() method of the Java Stream API. flatMapToDouble() is used to flatten streams that involve primitive double values. It is an essential tool for handling complex structures containing numerical data, allowing transformations from objects or other numeric streams into a DoubleStream.

Key Points

1. flatMapToDouble() converts each stream element into a DoubleStream and then flattens the result into a single DoubleStream.

2. It is particularly useful when dealing with collections of objects where each object may itself contain multiple double values.

3. This method simplifies operations that require mapping elements to multiple double values and then performing calculations or reductions on these values.

2. Program Steps

1. Create a Stream containing elements that can be transformed into double values.

2. Apply flatMapToDouble() to transform and flatten this stream into a DoubleStream.

3. Perform further operations, such as sum, average, etc., on the DoubleStream.

3. Code Program


public class StreamFlatMapToDoubleExample {

    public static void main(String[] args) {
        // Creating a stream of arrays
        Stream<double[]> arraysStream = Stream.of(new double[]{1.5, 2.3}, new double[]{3.7, 4.4});

        // Flattening the stream of arrays into a DoubleStream
        DoubleStream doubleStream = arraysStream.flatMapToDouble(DoubleStream::of);

        // Calculating the sum of all double values
        double sum = doubleStream.sum();
        System.out.println("Sum of all double values: " + sum);


Sum of all double values: 11.9


1. Stream.of(new double[]{1.5, 2.3}, new double[]{3.7, 4.4}) creates a stream consisting of arrays of double values.

2. arraysStream.flatMapToDouble(DoubleStream::of) uses flatMapToDouble to convert each array into a DoubleStream and then flattens all these streams into one.

3. doubleStream.sum() calculates the sum of all elements in the DoubleStream, resulting in the total sum of all double values in the original arrays.