如何在Java中使用Lambda实现IntUnaryOperator?
IntUnaryOperator代表一个接受int值并返回另一个int值的功能接口。它在java.util.function包中定义,并用作lambda表达式或方法引用的分配目标。它包含一个抽象方法:applyAsInt(),两个默认方法:compose()和Then()以及一个静态方法:identity()。
语法
@FunctionalInterface public interface IntUnaryOperator
示例
import java.util.function.IntUnaryOperator; public class IntUnaryOperatorLambdaTest1 { public static void main(String[] args) { IntUnaryOperator getSquare = intValue -> { // lambda expression int result = intValue * intValue; System.out.println("Getting square: "+ result); return result; }; IntUnaryOperator getNextInt = intValue -> { // lambda expression int result = intValue+1; System.out.println("Getting Next Int: "+ result); return result; }; IntUnaryOperator getSquareOfNext = getSquare.andThen(getNextInt); IntUnaryOperator getNextOfSquare = getSquare.compose(getNextInt); int input = 3; System.out.println("Input int value: "+ input); System.out.println(); int squareOfNext = getSquareOfNext.applyAsInt(input); System.out.println("Square of next int value: "+ squareOfNext); System.out.println(); int nextOfSquare = getNextOfSquare.applyAsInt(input); System.out.println("Next to square of int value: "+ nextOfSquare); } }
输出结果
Input int value : 3 Getting square : 9 Getting Next Int : 10 Square of next int value : 10 Getting Next Int : 4 Getting square : 16 Next to square of int value : 16
示例2
import java.util.concurrent.ThreadLocalRandom; import java.util.function.IntUnaryOperator; public class IntUnaryOperatorLambdaTest2 { public static int getRandonInt(){ return ThreadLocalRandom.current().nextInt(1000, 4999); } public static void main(String[] args) { IntUnaryOperator getInput = IntUnaryOperator.identity(); int identityVal = getInput.applyAsInt(getRandonInt()); System.out.println("Value passed as argument: "+ identityVal); System.out.println("Value passed as argument: "+ getInput.applyAsInt(getRandonInt())); System.out.println("Value passed as argument: "+ getInput.applyAsInt(getRandonInt())); } }
输出结果
Value passed as argument: 3141 Value passed as argument: 2635 Value passed as argument: 1179