Reduction Operations

Java-Reduction Operations

Reduction Operations

The Stream contains many terminal operations that return one value by combining the contents of a stream. These operations are called reduction operations. Many reduction operations perform a specific task. Consider the following program :

Program

Reduction Operations

Consider the min(), max(), findAny() and findFirst() methods in the program. They are reduction operations, because each reduces a stream to a single value. The stream API refers to these as special case reductions because they perform a specific function. Other special case reductions are also available, such as count( ), which counts the number of elements in a stream. Notice that the return type of some reduction operation is Optional. Optional is a generic class packaged in java.util and declared like:

Reduction Operations

Here, T specifies the element type. An Optional instance can either contain a value of type T or be empty. You can use isPresent( ) to determine if a value is present. Assuming that a value is available, it can be obtained by calling get( ). Next, notice that the type of min() and max()’s parameter is a Comparator. This Comparator is used to compare two elements in the stream. In the example, min() and max() are passed a method reference to Integer’s compare() method, which is used to implement a Comparator capable of comparing two Integers.

Program Source

import java.util.ArrayList;
import java.util.Optional;

public class Javaapp {

    public static void main(String[] args) {

        ArrayList<Integer> arylist = new ArrayList<Integer>();
        arylist.add(20);
        arylist.add(40);
        arylist.add(60);
        arylist.add(80);

        Optional fir = arylist.stream().findFirst();
        Optional any = arylist.stream().findAny();
        Optional max = arylist.stream().max(Integer::compare);
        Optional min = arylist.stream().min(Integer::compare);
        long telements = arylist.stream().count();

        System.out.println("any-> " + any.get());
        System.out.println("fir-> " + fir.get());
        System.out.println("min-> " + min.get());
        System.out.println("max-> " + max.get());
        System.out.println("Totel elements-> " + telements);
    }
}

Leave a Comment