对于Java中的函数式编程,Java 9版本随附Java中的IntUnaryOperator,让我们看一个示例-
import java.util.function.IntUnaryOperator; public class Demo{ public static void main(String args[]){ IntUnaryOperator op_1 = IntUnaryOperator.identity(); System.out.println("identity 函数:"); System.out.println(op_1.applyAsInt(56)); IntUnaryOperator op_2 = a -> 3 * a; System.out.println("applyAsInt 函数:"); System.out.println(op_2.applyAsInt(56)); IntUnaryOperator op_3 = a -> 3 * a; System.out.println("andThen 函数:"); op_3 = op_3.andThen(a -> 5 * a); System.out.println(op_3.applyAsInt(56)); IntUnaryOperator op_4 = a -> a / 6; System.out.println("compose 函数:"); op_4 = op_4.compose(a -> a * 9); System.out.println(op_4.applyAsInt(56)); } }
输出结果
identity 函数: 56 applyAsInt 函数: 168 andThen 函数: 840 compose 函数: 84
名为“demo”的类包含主要功能。在此,“身份”功能用于“ IntUnaryOperator”的实例。同样,其他函数(例如“ applyAsInt”,“ andThen”和“ compose”函数)与新创建的“ IntUnaryOperator”实例一起使用。每个函数调用的输出分别打印在控制台上。