Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8

Trong bài viết “Giới thiệu về Stream API trong Java 8” , chúng ta đã tìm hiểu về các đặc điểm, các làm việc của Stream trong Java 8. Ở bài viết này, tôi muốn giải thích kỹ hơn về cơ chế Lazy Evaluation của Stream trong Java 8.

Như chúng ta đã biết, Stream có một đặc điểm rất quan trọng là cho phép tối ưu hóa hiệu xuất của chương trình thông qua cơ chế lazy evaluation, nghĩa là chúng không được thực hiện cho đến khi cần thiết. Các hoạt động tính toán trên source data chỉ được thực hiện khi một terminal operation được khởi tạo và các source element chỉ được sử dụng khi cần.

Hãy xem ví dụ sau:

import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Stream;
 
import lombok.AllArgsConstructor;
import lombok.Data;
 
@Data
@AllArgsConstructor
class Employee {
    String name;
    String department;
    int salary;
}
 
class EmployeeRepository {
    private static final Map<Integer, Employee> employees = new HashMap<>();
    static {
        employees.put(1, new Employee("maixuanviet 1", "A", 50));
        employees.put(2, new Employee("maixuanviet 2", "B", 100));
        employees.put(3, new Employee("maixuanviet 3", "A", 150));
        employees.put(4, new Employee("maixuanviet 4", "B", 200));
    }
     
    public Employee findById(Integer id) {
        System.out.println("findById: " + id);
        return employees.get(id);
    }
}
 
class EmployeeFilter {
     
    public static Predicate<Employee> filterDepartmentEqualsWith(String department) {
        return e -> {
            System.out.println("filterDepartmentEqualsWith: " + e);
            return e.getDepartment().equals(department);
        };
    }
     
    public static Predicate<Employee> filterSalaryGreaterThan(int salary) {
        return e -> {
            System.out.println("filterSalaryGreaterThan: " + e);
            return e.getSalary() >= salary;
        };
    }
}
 
public class Java8StreamDeeply {
     
    public static void main(String[] args) {
        EmployeeRepository employeeRepository = new EmployeeRepository();
         
        Integer[] empIds = { 1, 2, 3, 4 };
         
        Stream.of(empIds)
          .map(employeeRepository::findById)
          .filter(EmployeeFilter.filterSalaryGreaterThan(100))
          .filter(EmployeeFilter.filterDepartmentEqualsWith("A"))
          .findFirst();
    }
}

Chạy chương trình trên, chúng ta có kết quả như sau:

findById: 1
filterSalaryGreaterThan: Employee(name=gpcoder 1, department=A, salary=50)
findById: 2
filterSalaryGreaterThan: Employee(name=gpcoder 2, department=B, salary=100)
filterDepartmentEqualsWith: Employee(name=gpcoder 2, department=B, salary=100)
findById: 3
filterSalaryGreaterThan: Employee(name=gpcoder 3, department=A, salary=150)
filterDepartmentEqualsWith: Employee(name=gpcoder 3, department=A, salary=150)

Như bạn thấy, chương trình của chúng ta có 4 phần tử nhưng chỉ 3 phần tử được thực thi. Tại sao vậy?

Trong ví dụ trên, tôi sử dụng 3 Intermediate operations: 1 map() và 2 filter() operations. Chúng ta có 4 phần tử ở Stream source, mỗi phần tử có thể sẽ được thực thi 1 lần qua tất cả intermediate operation.

Đầu tiên, nó sẽ kiểm tra tất cả các operation trên phần tử có id là 1. Vì salary của nó không thõa filter salary, nên xử lý sẽ chuyển sang phần tử kế tiếp – id là 2. Không thực hiện trên filter deparment.

Tiếp theo, id 2 chỉ thõa mãn điều kiện salary, không thõa mãn điều kiện department, nên xử lý chuyển sang phần tử kế tiếp – id là 3.

Tại id 3, thõa mãn tất cả điều kiện ở trên và Stream evaluate yêu cầu Terminal Operations findFirst() và trả về kết quả.

Các operation trên các phần tử còn lại sẽ không được thực thi – id 4.

Có thể thấy rằng, Stream hoạt động tuần tự trên từng phần tử của source, duyệt qua tất cả các immediate operations, rồi đến terminal operation, cuối cùng mới chuyển sang phần tử kế tiếp (có thể không chuyển sang phần tử kế tiếp nếu đã thõa mãn mong muốn của terminal operation).

Tóm lại, quá trình xử lý các Stream một cách lười biếng (lazy) cho phép tránh việc kiểm tra tất cả dữ liệu khi không cần thiết. Cách làm này giúp cho Stream hoạt động rất hiệu quả khi có nhiều intermediate operation và nguồn dữ liệu là lớn.

Bài viết đến đây là hết, sau bài này hy vọng các bạn hiểu rõ hơn về Stream trong Java 8 và vận dụng nó thích hợp để đạt được hiệu quả tốt hơn.

Related posts:

Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Hướng dẫn Java Design Pattern – Dependency Injection
Jackson Annotation Examples
Java Program to subtract two large numbers using Linked Lists
Redirect to Different Pages after Login with Spring Security
Java Program to Perform String Matching Using String Library
Spring Boot - Apache Kafka
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Concurrent Test Execution in Spring 5
Java Program to Implement WeakHashMap API
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Java Switch Statement
Jackson Ignore Properties on Marshalling
Intro to the Jackson ObjectMapper
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Spring Boot - Tomcat Port Number
Reading an HTTP Response Body as a String in Java
Java Program to Perform Cryptography Using Transposition Technique
A Guide to the ViewResolver in Spring MVC
Java Program to Generate Random Hexadecimal Byte
Refactoring Design Pattern với tính năng mới trong Java 8
Introduction to Apache Commons Text
Pagination and Sorting using Spring Data JPA
Java Program to Implement Segment Tree
Remove All Occurrences of a Specific Value from a List
Java Program to Implement Binary Search Tree
Java 8 Predicate Chain
Java Program to Implement Heap Sort Using Library Functions
Các kiểu dữ liệu trong java
Java Program to Implement Sorted Circular Doubly Linked List
Removing all Nulls from a List in Java
Java Program to Implement the Hungarian Algorithm for Bipartite Matching