jdk1.8 new feature - termination of Stream (example demonstration of reduction)

Posted by pplexr on Sat, 18 Dec 2021 08:16:03 +0100

1, Understanding of Stream

  • Stream is a key abstract concept for processing collections in Java 8. It can specify the operations you want to perform on collections, and can perform very complex operations such as finding, filtering and mapping data.
  • Use the Stream API to operate on collection data, similar to database queries executed using SQL.
  • Use the Stream API to perform operations in parallel.
  • The Stream API provides an efficient and easy-to-use way to process data.

2, What is a Stream

  • A Stream is a data channel used to manipulate a sequence of elements generated by a data source (collection, array, etc.).
  • Collections focus on data, and streams focus on computation.

3, Precautions for Stream

  • Stream itself does not store elements.
  • Stream does not change the source object. Instead, they return a new stream that holds the result.
  • Delayed execution during Stream operation. This means that they wait until the results are needed.

4, Operation steps of Stream API

1. Create Stream

  • A data source (such as collection and array) to obtain a stream.

2. Intermediate operation Stream

  • An intermediate operation chain that processes the data of the data source.
  • Multiple intermediate operations can be connected to form a pipeline. Unless the termination operation is triggered on the pipeline, the intermediate operation will not perform any processing, but all processing at one time when the operation is terminated is called "lazy evaluation".

3. Terminate Stream

  • A termination operation that executes an intermediate chain of operations and produces results.
  • The terminal operation generates results from the pipeline of the stream. The result can be any value that is not a stream, such as List, Integer, or even void.

5, Termination operation syntax for Stream

1. Reduction

methoddescribe
reduce(T iden, BinaryOperator b)You can combine the elements in the flow repeatedly to get a value. Return T
reduce(BinaryOperator b)You can combine the elements in the flow repeatedly to get a value. Return to optional < T >

6, Termination operation of Stream (example demonstration of reduction)

1. Create a Student entity class for presentation

package com.xz.springboot_java8.dya8.entity;
public class Student {
    private int id;//id
    private String name;//full name
    private int age;//Age
    private Score score;//Achievement (excellent, good, pass)

    public enum Score{
        EXCELLENT,
        GOOD,
        PASS
    }

    public Student(int id, String name, int age, Score score) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
    }
	//getter, setter and toString methods are omitted here
	.......
}

2. Example demonstration of reduction

  • The code is as follows

    package com.xz.springboot_java8.dya8;
    import com.xz.springboot_java8.dya8.entity.Student;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    /**
     * @description: Terminate operation
     *              reduce(T identity, BinaryOperator) You can combine the elements in the flow repeatedly to get a value.
     *              reduce(BinaryOperator b)	You can combine the elements in the flow repeatedly to get a value. Return to optional < T >
     * @author: xz
     */
    public class Test2 {
        public static void main(String[] args) {
            getreduce1();
            System.out.println("-------------");
            getreduce2();
        }
    
        /**
         *  reduce(T identity, BinaryOperator)Example
         */
        public static void getreduce1(){
            List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
            //The starting value is 0,
            //Assign 0 to X for the first time, and assign the first element in the list to y for addition. x=0;y=1,x+y=1
            //The second time, the first summation 1 is assigned to x, and the second element in the list is assigned to y for addition. x=1;y=2,x+y=3
            //The third and second summation 3 is assigned to x, and the third element in the list is assigned to y for addition. x=3;y=3,x+y=6
            //And so on, get the sum of all elements in the collection
            Integer sum = list.stream()
                    .reduce(0, (x, y) -> x + y);
            System.out.println(sum);
        }
    
        /**
         * reduce(BinaryOperator b)Example
         */
        public static void getreduce2(){
            List<Student> list = Arrays.asList(
                    new Student(1, "Li Si", 20,Student.Score.EXCELLENT),
                    new Student(2, "Zhang San", 19,Student.Score.GOOD ),
                    new Student(3, "Wang Wu", 24,Student.Score.PASS),
                    new Student(4, "Zhao Liu", 23, Student.Score.GOOD),
                    new Student(5, "xz", 21, Student.Score.PASS )
            );
            //Get the sum of the ages of all students
            Optional<Integer> opt = list.stream()
                    .map(Student::getAge)
                    .reduce(Integer::sum);
            System.out.println(opt.get());
    
        }
    }
    
  • The output results are as follows

Topics: Java Database Spring Boot