Reduction of Stream's Termination Operation [Java]

Reduction of termination operation for Stream

  1. T reduce(T identiey , BinaryOperation b);

    • You can combine elements in a stream over and over to get a value that returns a T-type of data
      • This repetitive combination is similar to recursive thinking
      • Here, the repetitive combination means that the method will automatically repeat itself. For example, if the binary function does an addition operation, the result of the two parameters'addition will be put on the first parameter of the binary function operation as the return value, and then the parameter will be added to the elements in the subsequent stream, so that the operation will continue to repeat.
      • That is, T apply(T t1,T t2) has been called repeatedly; Method
        • The result of each calculation is placed at position t1, and the operation is repeated until all the elements in the stream participate in the operation.
    • The first parameter identity in this method is the initial value
    • The second parameter b of this method is a binary function type interface instance

Note: The BinaryOperation < T > interface here inherits the BiFunction < T, T, T > interface

In large data, we often use mapping and reduction to get the sum of an attribute of all the data

eg: Here's an example: calculating the sum of natural numbers between 1 and 10

package stream flow.Terminate operation;

import java.util.Arrays;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) {
        /* 
        At this point we created a List collection of Integer type elements
         */
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        /*
        Here we add all the elements in the stream from 0 using the reduce() method
        
        Note: The return value type here is Integer type
         */
        Integer integer = list.stream().reduce(0,(e1,e2) -> {
            return e1 + e2;
        });
        System.out.println(integer);
    }
}
  1. Optional< T> reduce(BinaryOperator b);

    • You can combine elements in a stream over and over to get a value that returns the Optional < T > type

Note: The difference between this method and our previous reduce() method is that the return value type of this method is Optional < T>, while the return value type of the previous method is T

eg: Here's an example: calculating the sum of employees'wages

In this example, we mentioned two custom classes: we give the two custom classes:

  1. Employee class
package stream flow.Intermediate operation;

import java.util.Objects;

public class Employee{
    private int bianHao;
    private String name;
    private int age;
    private double salary;

    public Employee(){

    }
    public Employee(int bianHao, String name, int age, double salary){
        this.bianHao = bianHao;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public int getBianHao() {
        return bianHao;
    }

    public void setBianHao(int bianHao) {
        this.bianHao = bianHao;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "bianHao=" + bianHao +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return bianHao == employee.bianHao &&
                age == employee.age &&
                Double.compare(employee.salary, salary) == 0 &&
                Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(bianHao, name, age, salary);
    }
}

  1. EmployeeDate class
package stream flow.Intermediate operation;

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

public class EmployeeDate {
    public EmployeeDate(){

    }
    public static List<Employee> getEmployeeDate(){
        List<Employee>  list = new ArrayList<>();
        Employee e1 = new Employee(1001,"pony",20,8001);
        Employee e2 = new Employee(1002,"Jack Ma",47,8701);
        Employee e3 = new Employee(1003,"Liu Qiangdong",34,8401);
        Employee e4 = new Employee(1004,"Cao Cao",32,4501);
        Employee e5 = new Employee(1005,"Liu Bei",12,5401);
        Employee e6 = new Employee(1006,"Zhang Fei",21,6601);

        list.add(e1);
        list.add(e2);
        list.add(e3);
        list.add(e4);
        list.add(e5);
        list.add(e6);
        return list;
    }
}

Here we give the main function:

package stream flow.Terminate operation;

import stream flow.Intermediate operation.Employee;
import stream flow.Intermediate operation.EmployeeDate;
import java.util.stream.Stream;
import java.util.Optional;

import java.util.List;

public class Demo2 {
    public static void main(String[] args) {
        List<Employee> list = EmployeeDate.getEmployeeDate();
        //Here's how lambda expressions are used
//        Stream<Double> stream = list.stream().map(e -> e.getSalary());
        /*
        Here is the third case where method references are used:Class:Non-static method
         */
        Stream<Double> stream = list.stream().map(Employee :: getSalary);
        Optional<Double> optional = stream.reduce((e1,e2) ->{
            return e1 + e2;
        });
        System.out.println(optional);

    }
}

BinaryOperation< T> extends BiFunction<T,T,T>

  • The apply() method declaration in the BinaryOperation < T > interface takes the form of:

    • T apply(T t1 , T t2);
  • The apply() method declaration in BiFunction <T, U, R>interfaces takes the form of:

    • T apply(U u , R r);

Keywords: Java Back-end

Added by BuzFortuna on Fri, 24 Dec 2021 22:35:21 +0200