How do I use the ToDoubleFunction functional interface in Java?

The ToDoubleFunction is a functional interface in Java that is part of the java.util.function package. It represents a function that takes a single input of type T and produces a double as a result. This is useful when we need to perform operations that convert objects to primitive double values, such as extracting a numeric property from an object or performing calculations.

Here’s how we can use the ToDoubleFunction interface:

Functional Method

The functional method of ToDoubleFunction<T> is:

double applyAsDouble(T value);

This method takes an input of type T and returns a double.


How to Use ToDoubleFunction

We can use it with:
1. Lambda expressions
2. Method references


Example 1: Extracting a Property from an Object

Suppose we have a class called Product with a price field, and we want to extract the price as a double using ToDoubleFunction:

package org.kodejava.util.function;

import java.util.function.ToDoubleFunction;

class TheProduct {
    private String name;
    private double price;

    public TheProduct(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public double getPrice() {
        return price;
    }
}

public class ToDoubleFunctionExample {
    public static void main(String[] args) {
        TheProduct product = new TheProduct("Laptop", 999.99);

        // Using a lambda expression
        ToDoubleFunction<TheProduct> getPrice = p -> p.getPrice();

        // Applying the function
        double price = getPrice.applyAsDouble(product);
        System.out.println("Price: " + price);

        // Using a method reference
        ToDoubleFunction<TheProduct> getPriceRef = TheProduct::getPrice;

        // Applying the function again
        double priceRef = getPriceRef.applyAsDouble(product);
        System.out.println("Price using method reference: " + priceRef);
    }
}

Output:

Price: 999.99
Price using method reference: 999.99

Example 2: Performing a Calculation

We can also use ToDoubleFunction to calculate something based on an object. For example:

package org.kodejava.util.function;

import java.util.function.ToDoubleFunction;

class Circle {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }
}

public class ToDoubleFunctionExample2 {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);

        // Lambda to calculate the area of a circle
        ToDoubleFunction<Circle> calculateArea = c -> Math.PI * Math.pow(c.getRadius(), 2);

        double area = calculateArea.applyAsDouble(circle);
        System.out.println("Circle area: " + area);
    }
}

Output:

Circle area: 78.53981633974483

Use in Streams

ToDoubleFunction is often used in streams with methods like .mapToDouble. Here’s an example:

package org.kodejava.util.function;

import java.util.ArrayList;
import java.util.List;

public class ToDoubleFunctionExample3 {
    public static void main(String[] args) {
        List<TheProduct> products = new ArrayList<>();
        products.add(new TheProduct("Book", 12.99));
        products.add(new TheProduct("Pen", 1.99));
        products.add(new TheProduct("Notebook", 4.99));

        // Calculate the total price using mapToDouble
        double totalPrice = products.stream()
                .mapToDouble(TheProduct::getPrice) // ToDoubleFunction in action
                .sum();

        System.out.println("Total price: " + totalPrice);
    }
}

Output:

Total price: 19.97

Summary

  • The ToDoubleFunction interface is commonly used to convert objects into double values.
  • Its method applyAsDouble provides a clean way to define this conversion or computation.
  • It works well with lambdas, method references, and stream operations.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.