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:

Spring MVC Custom Validation
Deque và ArrayDeque trong Java
Spring Cloud – Bootstrapping
Java Program to Implement Hash Trie
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Java Program to Implement Bit Array
Java Program to Implement AVL Tree
Java Program to Implement Binomial Heap
Spring Boot - Admin Server
Java 9 Stream API Improvements
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Java Program to Implement Naor-Reingold Pseudo Random Function
Hướng dẫn Java Design Pattern – Service Locator
Remove All Occurrences of a Specific Value from a List
Java Program to Perform Cryptography Using Transposition Technique
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Command-Line Arguments in Java
A Comparison Between Spring and Spring Boot
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
How to Replace Many if Statements in Java
Testing an OAuth Secured API with Spring MVC
Java Program to Implement RoleList API
Java Program to Implement Self organizing List
Java Program to Implement Insertion Sort
Thao tác với tập tin và thư mục trong Java
Java Program to Find Maximum Element in an Array using Binary Search
List Interface trong Java
A Quick JUnit vs TestNG Comparison
Java Program to Find Nearest Neighbor Using Linear Search
Cài đặt và sử dụng Swagger UI
A Guide to Java HashMap
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not