Home > Java > javaTutorial > body text

How to implement lazy evaluation in java

WBOY
Release: 2023-05-04 12:28:06
forward
1128 people have browsed it

Explanation

1. Lazy evaluation is the process of delaying the evaluation of an expression until needed. Java is strictly immediate assignment evaluation.

2. It can be rewritten into a lazy-evaluated version using lambda expressions and higher-order functions.

Example

public class LazySample {
    public static void main(String[] args) {
        //这是一个lambda表达式,表现为闭包
        UnaryOperator<Integer> add = t -> {
            System.out.println("executing add");
            return t + t;
        };
      //这是一个lambda表达式,表现为闭包
        UnaryOperator<Integer> multiply = t -> {
            System.out.println("executing multiply");
            return t * t;
        };
        //传递Lambda闭包而不是普通函数
        System.out.println(addOrMultiply(true, add, multiply, 4));
        System.out.println(addOrMultiply(false, add, multiply, 4));
    }
 
    //这是一个高阶函数
    static <T, R> R addOrMultiply(
            boolean add, Function<T, R> onAdd,
            Function<T, R> onMultiply, T t
    ) {
        // Java的?会懒惰计算表达式,因此仅执行所需的方法
        return (add ? onAdd.apply(t) : onMultiply.apply(t));
    }
}
Copy after login

The above is the detailed content of How to implement lazy evaluation in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!