Java DoubleStream

1. Introduction

This tutorial introduces the DoubleStream class of the Java Stream API. DoubleStream is a stream of double primitive values which supports various methods to perform sequential and parallel aggregate operations. This tutorial covers the key methods of DoubleStream that are commonly used in data processing and calculations.

Java DoubleStream Commonly Used Methods:

1. sum() computes the sum of elements in the stream.

2. average() calculates the average of elements.

3. max() and min() find the maximum and minimum element respectively.

4. forEach() is used to iterate over each element.

5. map() transforms each element in the stream.

6. filter() filters elements based on a predicate.

7. boxed() boxes elements into their wrapper class (Double).

2. Program Steps

1. Create a DoubleStream.

2. Apply sum, average, max, min, and other operations.

3. Use the map and filter to modify and filter the stream.

4. Convert the DoubleStream to other forms or collect results.

3. Code Program

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

public class DoubleStreamExample {

    public static void main(String[] args) {
        // Creating a DoubleStream
        DoubleStream doubleValues = DoubleStream.of(1.5, 2.5, 3.5, 4.5, 5.5);

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

        // Resetting stream for next operation
        doubleValues = DoubleStream.of(1.5, 2.5, 3.5, 4.5, 5.5);

        // Calculating the average of all elements
        OptionalDouble average = doubleValues.average();
        average.ifPresent(avg -> System.out.println("Average of values: " + avg));

        // Finding maximum value
        doubleValues = DoubleStream.of(1.5, 2.5, 3.5, 4.5, 5.5);
        OptionalDouble max = doubleValues.max();
        max.ifPresent(m -> System.out.println("Maximum value: " + m));

        // Filtering and mapping
        doubleValues = DoubleStream.of(1.5, 2.5, 3.5, 4.5, 5.5);
        doubleValues.filter(d -> d > 3.0).map(d -> d * 2).forEach(d -> System.out.println("Filtered and mapped value: " + d));
    }
}

Output:

Sum of all values: 17.5
Average of values: 3.5
Maximum value: 5.5
Filtered and mapped value: 7.0
Filtered and mapped value: 9.0
Filtered and mapped value: 11.0

Explanation:

1. DoubleStream.of(1.5, 2.5, 3.5, 4.5, 5.5) initializes a DoubleStream with given values.

2. .sum() computes the total sum of the stream elements.

3. .average() calculates the average value of the elements, returning an OptionalDouble, which is printed if present.

4. .max() finds the maximum value in the stream, also returned as an OptionalDouble.

5. The stream is then filtered to include only elements greater than 3.0, and each element is doubled with .map(). Results are printed using .forEach().

4. Real-Time Example

In this section, let's dive deeper into DoubleStream, showcasing practical applications of its methods through a scenario where we analyze temperature data. We'll calculate various statistics and transform the data using DoubleStream methods.

Program Steps

1. Initialize a stream with temperature data.

2. Calculate basic statistics: sum, average, maximum, and minimum.

3. Convert Celsius temperatures to Fahrenheit.

4. Filter out extreme temperature values.

5. Box primitive double values into Double objects for further processing.

Code Program

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

public class TemperatureAnalysis {

    public static void main(String[] args) {
        // Sample temperatures in Celsius from a week's weather data
        DoubleStream temperatures = DoubleStream.of(16.5, 18.3, 17.5, 15.0, 14.8, 21.3, 20.6);

        // Calculate total heat accumulation
        double totalHeat = temperatures.sum();
        System.out.println("Total heat accumulation: " + totalHeat);

        // Resetting the stream to calculate average temperature
        temperatures = DoubleStream.of(16.5, 18.3, 17.5, 15.0, 14.8, 21.3, 20.6);
        OptionalDouble averageTemp = temperatures.average();
        averageTemp.ifPresent(avg -> System.out.println("Average temperature: " + avg));

        // Finding maximum and minimum temperature
        temperatures = DoubleStream.of(16.5, 18.3, 17.5, 15.0, 14.8, 21.3, 20.6);
        temperatures.max().ifPresent(max -> System.out.println("Maximum temperature: " + max));
        temperatures = DoubleStream.of(16.5, 18.3, 17.5, 15.0, 14.8, 21.3, 20.6);
        temperatures.min().ifPresent(min -> System.out.println("Minimum temperature: " + min));

        // Convert Celsius to Fahrenheit
        temperatures = DoubleStream.of(16.5, 18.3, 17.5, 15.0, 14.8, 21.3, 20.6);
        DoubleStream fahrenheitTemperatures = temperatures.map(c -> c * 9 / 5 + 32);
        fahrenheitTemperatures.forEach(f -> System.out.println("Temperature in Fahrenheit: " + f));

        // Filter out unusually cold days below 15 degrees Celsius
        temperatures = DoubleStream.of(16.5, 18.3, 17.5, 15.0, 14.8, 21.3, 20.6);
        DoubleStream coldDays = temperatures.filter(temp -> temp < 15);
        List<Double> coldDayList = coldDays.boxed().collect(Collectors.toList());
        System.out.println("Cold days (below 15C): " + coldDayList);
    }
}

Output:

Total heat accumulation: 124.0
Average temperature: 17.642857142857142
Maximum temperature: 21.3
Minimum temperature: 14.8
Temperature in Fahrenheit: 61.7
Temperature in Fahrenheit: 64.94
Temperature in Fahrenheit: 63.5
Temperature in Fahrenheit: 59.0
Temperature in Fahrenheit: 58.64
Temperature in Fahrenheit: 70.34
Temperature in Fahrenheit: 69.08
Cold days (below 15C): [14.8]

Explanation:

1. DoubleStream.of() initializes a stream of double values representing temperatures in Celsius.

2. sum() calculates the total heat accumulation across the data points.

3. average() computes the average of the temperatures.

4. max() and min() find the highest and lowest temperatures, respectively.

5. map() converts each Celsius temperature to Fahrenheit.

6. filter() screens out days with temperatures below 15°C.

7. boxed() converts the primitive double values into Double objects, which are then collected into a list.

Comments