Java Collectors summingDouble() Method

The summingDouble() method in Java, part of the java.util.stream.Collectors class, is used to calculate the sum of a double-valued function applied to the elements of a stream. This method is useful when you need to compute the sum of certain properties of the elements in a stream.

Table of Contents

  1. Introduction
  2. summingDouble() Method Syntax
  3. Understanding summingDouble()
  4. Examples
    • Basic Usage
    • Using summingDouble() with Custom Objects
  5. Real-World Use Case
  6. Conclusion

Introduction

The summingDouble() method returns a Collector that produces the sum of a double-valued function applied to the input elements. This method is particularly useful for aggregating numeric data from a stream.

summingDouble() Method Syntax

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

public static <T> Collector<T, ?, Double> summingDouble(ToDoubleFunction<? super T> mapper)

Parameters:

  • mapper: A function that extracts a double-valued property from an element.

Returns:

  • A Collector that produces the sum of the extracted double values.

Throws:

  • This method does not throw any exceptions.

Understanding summingDouble()

The summingDouble() method allows you to sum the double values derived from the elements of a stream. This is useful in scenarios where you need to aggregate numeric data from a collection of objects.

Examples

Basic Usage

To demonstrate the basic usage of summingDouble(), we will create a list of double values and calculate their sum.

Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SummingDoubleExample {
    public static void main(String[] args) {
        List<Double> numbers = Arrays.asList(1.0, 2.5, 3.8, 4.2, 5.0);

        // Calculate the sum of the numbers
        Double sum = numbers.stream()
                            .collect(Collectors.summingDouble(Double::doubleValue));

        System.out.println("Sum: " + sum);
    }
}

Output:

Sum: 16.5

Using summingDouble() with Custom Objects

This example shows how to use summingDouble() with a stream of custom objects to calculate the sum of a specific property.

Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SummingDoubleCustomObjectExample {
    static class Product {
        String name;
        double price;

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

        double getPrice() {
            return price;
        }
    }

    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
            new Product("Product A", 10.0),
            new Product("Product B", 20.5),
            new Product("Product C", 15.8),
            new Product("Product D", 30.2),
            new Product("Product E", 25.0)
        );

        // Calculate the sum of the prices of the products
        Double totalPrice = products.stream()
                                    .collect(Collectors.summingDouble(Product::getPrice));

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

Output:

Total Price: 101.5

Real-World Use Case

Calculating Total Sales Revenue

In real-world applications, the summingDouble() method can be used to calculate the total sales revenue from a list of sales transactions.

Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class TotalRevenueExample {
    static class Transaction {
        double amount;

        Transaction(double amount) {
            this.amount = amount;
        }

        double getAmount() {
            return amount;
        }
    }

    public static void main(String[] args) {
        List<Transaction> transactions = Arrays.asList(
            new Transaction(100.0),
            new Transaction(200.0),
            new Transaction(150.0),
            new Transaction(50.0)
        );

        // Calculate the total revenue using summingDouble()
        Double totalRevenue = transactions.stream()
                                          .collect(Collectors.summingDouble(Transaction::getAmount));

        System.out.println("Total Revenue: " + totalRevenue);
    }
}

Output:

Total Revenue: 500.0

Conclusion

The Collectors.summingDouble() method is used to calculate the sum of a double-valued function applied to the elements of a stream. This method is particularly useful for aggregating numeric data from a collection of objects. By understanding and using this method, you can efficiently manage summing operations in your Java applications.

Comments