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 Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
How to Get All Dates Between Two Dates?
Logging a Reactive Sequence
Java Program to Implement PriorityQueue API
Notify User of Login From New Device or Location
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Upload and Display Excel Files with Spring MVC
How to Get a Name of a Method Being Executed?
More Jackson Annotations
Java Program to Implement Sorted Array
Immutable Objects in Java
Derived Query Methods in Spring Data JPA Repositories
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Java Program to Implement Aho-Corasick Algorithm for String Matching
Converting a List to String in Java
Hướng dẫn Java Design Pattern – Singleton
Spring Boot: Customize the Jackson ObjectMapper
Java Program to Check whether Directed Graph is Connected using DFS
Filtering a Stream of Optionals in Java
Shuffling Collections In Java
Spring Boot: Customize Whitelabel Error Page
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Java Program to Implement AVL Tree
Quick Guide to Spring MVC with Velocity
Java Program to Implement Direct Addressing Tables
Spring Boot - Application Properties
Sending Emails with Java
Call Methods at Runtime Using Java Reflection
Spring Boot Application as a Service
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java
A Guide to WatchService in Java NIO2