Java 8 Stream introduction

Keywords: Java Database SQL

Introduction:

The Java 8 API adds a new abstraction called Stream, which allows you to process data in a declarative way, under the java.util.stream package.

Stream provides a high-level abstraction of Java set operations and expressions in an intuitive way similar to querying data from a database using SQL statements.

Stream API can greatly improve the productivity of Java programmers and make them write efficient, clean and concise code.

This style regards the set of elements to be processed as a flow, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc.

The element flow is processed by intermediate operation in the pipeline, and the final operation gets the result of the previous processing.

Generating stream

In Java 8, the collection interface has two methods to generate streams:

stream() − creates a serial stream for the collection.

parallelStream() − creates a parallel stream for the collection.

Method example:

public class Employee {
    //Employee number
    private Long empno;
    //Employee name
    private String ename;
    //salary
    private Integer salary;
    //Department No
    private Integer deptno;

    public Employee(Long empno, String ename, Integer salary, Integer deptno) {
        this.empno = empno;
        this.ename = ename;
        this.salary = salary;
        this.deptno = deptno;
    }

  @Override
    public String toString() {
        return "Employee{" +
                "empno=" + empno +
                ", ename='" + ename + '\'' +
                ", salary=" + salary +
                ", deptno=" + deptno +
                '}';
    }
   //Omit get and set methods
}
Employee e1 = new Employee(7369L, "SMITH", 800, 20);
Employee e2 = new Employee(7499L, "ALLEN", 1600, 30);
Employee e3 = new Employee(7521L, "WARD", 1250, 30);
Employee e4 = new Employee(7782L, "CLARK", 2450, 10);
Employee e5 = new Employee(7876L, "ADAMS", 1100, 20);

List<Employee> employees = Arrays.asList(e1, e2, e3, e4, e5);

1. forEach method

forEach Method for iteration stream Every element in the stream
employees.stream().forEach(System.out::println);

//Execution result:
Employee{empno=7369, ename='SMITH', salary=800, deptno=20}
Employee{empno=7499, ename='ALLEN', salary=1600, deptno=30}
Employee{empno=7521, ename='WARD', salary=1250, deptno=30}
Employee{empno=7782, ename='CLARK', salary=2450, deptno=10}
Employee{empno=7876, ename='ADAMS', salary=1100, deptno=20}

2. map method

map Method is used to pair stream One to one mapping of data in a stream
//Get names of all employees
List<String> listName = employees.stream()
                .map(employee -> employee.getEname())
                .collect(Collectors.toList());
        listName.stream().forEach(System.out::println);

//Execution result:
SMITH
ALLEN
WARD
CLARK
ADAMS

3. mapToInt/mapToLong/mapToDouble method

These methods are mainly used to generate a single statistical result for the elements in stream stream
  //Get the sum of all employees' salaries
        int totalSalary = employees.stream()
                .mapToInt(employee -> employee.getSalary()).sum();
        System.out.println("total salary:" + total salary);

Execution result:
Total salary: 7200

4. filter method

The filter method is used to filter the data in the stream according to the set conditions
 //Employees earning more than 1500
List<Employee> filterEmp = employees.stream()
    .filter(employee -> employee.getSalary()>1500)
    .collect(Collectors.toList());

filterEmp.stream().forEach(System.out::println);

Execution result:
Employee{empno=7499, ename='ALLEN', salary=1600, deptno=30}
Employee{empno=7782, ename='CLARK', salary=2450, deptno=10}

5. sorted method

sorted Method to sort elements in a stream
//Rank employees by salary
List<Employee> sortedEmp = employees.stream()
    .sorted(Comparator.comparing(Employee::getSalary))
    .collect(Collectors.toList());
sortedEmp.stream().forEach(System.out::println);

//Execution result:
Employee{empno=7369, ename='SMITH', salary=800, deptno=20}
Employee{empno=7876, ename='ADAMS', salary=1100, deptno=20}
Employee{empno=7521, ename='WARD', salary=1250, deptno=30}
Employee{empno=7499, ename='ALLEN', salary=1600, deptno=30}
Employee{empno=7782, ename='CLARK', salary=2450, deptno=10}

//Rank employees by salary
List<Employee> sortedEmp = employees.stream()
    .sorted(Comparator.comparing(Employee::getSalary).reversed())
    .collect(Collectors.toList());
sortedEmp.stream().forEach(System.out::println);

//Execution result:
Employee{empno=7782, ename='CLARK', salary=2450, deptno=10}
Employee{empno=7499, ename='ALLEN', salary=1600, deptno=30}
Employee{empno=7521, ename='WARD', salary=1250, deptno=30}
Employee{empno=7876, ename='ADAMS', salary=1100, deptno=20}
Employee{empno=7369, ename='SMITH', salary=800, deptno=20}


//Sort by employee department number and then by salary
List<Employee> sortList = employees.stream()
    .sorted(Comparator.comparing(Employee::getDeptno).thenComparing(Employee::getSalary))
    .collect(Collectors.toList());
sortList.stream().forEach(rec-> System.out.println(rec));

//Execution result:
Employee{empno=7782, ename='CLARK', salary=2450, deptno=10}
Employee{empno=7369, ename='SMITH', salary=800, deptno=20}
Employee{empno=7876, ename='ADAMS', salary=1100, deptno=20}
Employee{empno=7521, ename='WARD', salary=1250, deptno=30}
Employee{empno=7499, ename='ALLEN', salary=1600, deptno=30}

6. Collectors

Collectors Class implements many reduction operations, such as converting streams to collections and aggregate elements. Collectors Can be used to return a list or string
//Classification by department number of employee
Map<Integer, List<Employee>> map = employees.stream()
    .collect(Collectors.groupingBy(employee -> employee.getDeptno()));

for(Map.Entry<Integer, List<Employee>> entry : map.entrySet()) {
    System.out.println("key: " + entry.getKey() + "  value: " + entry.getValue());
}

System.out.println();

//Get the employee's name and splice it with ","
String nameStr= employees.stream()
    .map(employee -> employee.getEname())
    .collect(Collectors.joining(","));
    
System.out.println(nameStr);

//Execution result:
key: 20  value: [Employee{empno=7369, ename='SMITH', salary=800, deptno=20}, Employee{empno=7876, ename='ADAMS', salary=1100, deptno=20}]
key: 10  value: [Employee{empno=7782, ename='CLARK', salary=2450, deptno=10}]
key: 30  value: [Employee{empno=7499, ename='ALLEN', salary=1600, deptno=30}, Employee{empno=7521, ename='WARD', salary=1250, deptno=30}]

SMITH,ALLEN,WARD,CLARK,ADAMS

7. Method series

The Stream API provides multiple methods that can be concatenated in one line of code at the same time
 //Get the names of employees in department 20, sorted by salary from high to low
List<String> listName= employees.stream()
    .filter(employee -> employee.getDeptno().equals(20))
    .sorted(Comparator.comparing(Employee::getSalary).reversed())
    .map(employee -> employee.getEname())
    .collect(Collectors.toList());

listName.stream().forEach(System.out::println);

Execution result:
ADAMS
SMITH

Conclusion:

The Stream API of Java8 provides many methods to filter and sort collections. Compared with java7, it greatly simplifies the development of code and is recommended to use more.

Published 3 original articles, won praise 0, visited 110
Private letter follow

Posted by jack5100nv on Mon, 13 Jan 2020 23:20:56 -0800