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:

Java Program to Implement Borwein Algorithm
Java Program to Implement Trie
Spring Boot - Sending Email
Custom Thread Pools In Java 8 Parallel Streams
Java Program to Implement Uniform-Cost Search
The Registration API becomes RESTful
Java Program to Implement Euler Circuit Problem
Convert Time to Milliseconds in Java
Java Program to Implement Floyd-Warshall Algorithm
A Guide to the finalize Method in Java
Lập trình hướng đối tượng (OOPs) trong java
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
Java Program to Find kth Largest Element in a Sequence
Runnable vs. Callable in Java
Add Multiple Items to an Java ArrayList
Java Program to Implement Max-Flow Min-Cut Theorem
A Guide to the ResourceBundle
“Stream has already been operated upon or closed” Exception in Java
Recommended Package Structure of a Spring Boot Project
How to Convert List to Map in Java
Java – Random Long, Float, Integer and Double
Functional Interfaces in Java 8
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Setting Up Swagger 2 with a Spring REST API
Kết hợp Java Reflection và Java Annotations
Retrieve User Information in Spring Security
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Adding Parameters to HttpClient Requests
Spring Boot - Build Systems
Java Program to Implement Coppersmith Freivald’s Algorithm
Java Program to Implement D-ary-Heap
Java Program to Find Whether a Path Exists Between 2 Given Nodes