Home  >  Article  >  Java  >  How to implement lazy evaluation in java

How to implement lazy evaluation in java

WBOY
WBOYforward
2023-05-04 12:28:061129browse

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));
    }
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete