Java Stream mapToDouble() Method

The mapToDouble() method in Java is a part of the java.util.stream.Stream interface. In this guide, we will learn how to use mapToDouble() method in Java with practical examples and real-world use cases to better understand its usage.

Table of Contents

  1. Introduction
  2. mapToDouble() Method Syntax
  3. Examples
    • Basic Usage
    • Using mapToDouble() with Complex Transformations
  4. Real-World Use Case
  5. Conclusion

Introduction

The Stream.mapToDouble() method in Java is used to transform each element of a stream into a double value, returning a DoubleStream. It is useful for handling primitive double values efficiently.

This is useful for performing numerical operations or calculations on the elements of the stream.

mapToDouble() is commonly used when working with streams of objects that need to be converted to double values, enabling optimized processing for numeric streams.

mapToDouble() Method Syntax

The syntax for the mapToDouble() method is as follows:

DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)

Parameters:

  • mapper: A function to apply to each element of the stream, which produces a double value.

Returns:

  • A new DoubleStream consisting of the results of applying the given function to the elements of the original stream.

Throws:

  • This method does not throw any exceptions.

Examples

Basic Usage

To demonstrate the basic usage of mapToDouble(), we will create a Stream of integers and use mapToDouble() to transform each integer into its square root.

Example

import java.util.stream.DoubleStream;
import java.util.stream.Stream;

public class MapToDoubleExample {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 4, 9, 16, 25);

        // Use mapToDouble() to transform each integer into its square root
        DoubleStream doubleStream = stream.mapToDouble(Math::sqrt);

        // Print the transformed elements
        doubleStream.forEach(System.out::println);
    }
}

Output:

1.0
2.0
3.0
4.0
5.0

Using mapToDouble() with Complex Transformations

This example shows how to use mapToDouble() to calculate the lengths of strings in a stream.

Example

import java.util.stream.DoubleStream;
import java.util.stream.Stream;

public class MapToDoubleComplexExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry");

        // Use mapToDouble() to calculate the length of each string
        DoubleStream doubleStream = stream.mapToDouble(String::length);

        // Print the transformed elements
        doubleStream.forEach(System.out::println);
    }
}

Output:

5.0
6.0
6.0

Real-World Use Case

Calculating Average Scores

In real-world applications, the mapToDouble() method can be used to calculate the average score of a list of students.

Example

import java.util.stream.DoubleStream;
import java.util.stream.Stream;

public class MapToDoubleRealWorldExample {
    static class Student {
        String name;
        int score;

        Student(String name, int score) {
            this.name = name;
            this.score = score;
        }

        int getScore() {
            return score;
        }
    }

    public static void main(String[] args) {
        Stream<Student> students = Stream.of(
            new Student("Alice", 85),
            new Student("Bob", 90),
            new Student("Charlie", 78)
        );

        // Use mapToDouble() to transform each student into their score and calculate the average
        DoubleStream scores = students.mapToDouble(Student::getScore);
        double averageScore = scores.average().orElse(0.0);

        // Print the average score
        System.out.println("Average Score: " + averageScore);
    }
}

Output:

Average Score: 84.33333333333333

Conclusion

The Stream.mapToDouble() method is used to transform each element of the stream into a double-valued stream. This method is particularly useful for performing numerical operations or calculations on the elements of the stream.

By understanding and using this method, you can efficiently manage and process streams of values in your Java applications, performing necessary numerical transformations and calculations as needed.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top