Java Collectors reducing() Method

The reducing() method in Java, part of the java.util.stream.Collectors class, is used to perform a reduction on the elements of a stream, producing a single result. This method is useful when you need to combine the elements of a stream into a single summary result, such as the sum of all elements.

Table of Contents

  1. Introduction
  2. reducing() Method Syntax
  3. Understanding reducing()
  4. Examples
    • Basic Usage
    • Using reducing() with Binary Operator and Identity Value
    • Using reducing() with a Binary Operator, Identity Value, and Mapper Function
  5. Real-World Use Case
  6. Conclusion

Introduction

The reducing() method returns a Collector that performs a reduction on the elements of a stream, combining them into a single result. There are multiple overloaded versions of this method to provide flexibility in how the reduction is performed.

reducing() Method Syntax

There are three overloaded versions of the reducing() method:

  1. Basic reducing() method with a binary operator:
public static <T> Collector<T, ?, Optional<T>> reducing(BinaryOperator<T> op)
  1. reducing() method with an identity value and a binary operator:
public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op)
  1. reducing() method with an identity value, a mapper function, and a binary operator:
public static <T, U> Collector<T, ?, U> reducing(U identity, Function<? super T, ? extends U> mapper, BinaryOperator<U> op)

Parameters:

  • op: A BinaryOperator that combines two elements.
  • identity (optional): An identity value that is the initial value and the default result if the stream is empty.
  • mapper (optional): A function that maps the elements before combining them.

Returns:

  • A Collector that performs a reduction on the input elements.

Throws:

  • This method does not throw any exceptions.

Understanding reducing()

The reducing() method allows you to reduce the elements of a stream into a single result using a binary operator. Depending on the version used, you can also provide an identity value and a mapper function to transform the elements before reducing them.

Examples

Basic Usage

To demonstrate the basic usage of reducing(), we will create a list of integers and find the sum of all elements using a binary operator.

Example

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

public class ReducingExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Find the sum of all elements using reducing()
        Optional<Integer> sum = numbers.stream()
                                       .collect(Collectors.reducing(Integer::sum));

        sum.ifPresent(s -> System.out.println("Sum: " + s));
    }
}

Output:

Sum: 15

Using reducing() with Binary Operator and Identity Value

This example shows how to use reducing() with an identity value and a binary operator to find the product of all elements.

Example

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

public class ReducingWithIdentityExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Find the product of all elements using reducing() with identity
        Integer product = numbers.stream()
                                 .collect(Collectors.reducing(1, (a, b) -> a * b));

        System.out.println("Product: " + product);
    }
}

Output:

Product: 120

Using reducing() with a Binary Operator, Identity Value, and Mapper Function

This example shows how to use reducing() with a mapper function to find the sum of the squares of all elements.

Example

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

public class ReducingWithMapperExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Find the sum of the squares of all elements using reducing() with a mapper
        Integer sumOfSquares = numbers.stream()
                                      .collect(Collectors.reducing(0, n -> n * n, Integer::sum));

        System.out.println("Sum of Squares: " + sumOfSquares);
    }
}

Output:

Sum of Squares: 55

Real-World Use Case

Calculating Total Revenue

In real-world applications, the reducing() method can be used to calculate the total 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 reducing()
        Double totalRevenue = transactions.stream()
                                          .collect(Collectors.reducing(
                                              0.0,
                                              Transaction::getAmount,
                                              Double::sum
                                          ));

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

Output:

Total Revenue: 500.0

Conclusion

The Collectors.reducing() method is used to perform a reduction on the elements of a stream, combining them into a single result. This method is particularly useful for summarizing the elements of a stream. By understanding and using this method, you can efficiently manage reduction operations in your Java applications.

Comments