如何在 Java 中使用 lambda 表达式实现 LongUnaryOperator?
java 8object oriented programmingprogramming更新于 2025/4/23 9:52:17
LongUnaryOperator 是来自 java.util.function 包的一个函数式接口。该函数式接口接受一个 长值 操作数并返回一个 长值 结果。LongUnaryOperator 接口可用作 lambda表达式 和 方法引用 的赋值目标。它包含一个抽象方法:applyAsLong()、一个静态方法:identity() 以及两个默认方法:andThen() 和 compose()。
语法
@FunctionalInterface public interface LongUnaryOperator long applyAsLong(long operand); }
示例
import java.util.function.LongUnaryOperator; public class LongUnaryOperatorTest { public static void main(String args[]) { LongUnaryOperator getSquare = longValue -> { // lambda long result = longValue * longValue; System.out.println("Getting square: " + result); return result; }; LongUnaryOperator getNextValue = longValue -> { // lambda long result = longValue + 1; System.out.println("Getting Next value: " + result); return result; }; LongUnaryOperator getSquareOfNext = getSquare.andThen(getNextValue); LongUnaryOperator getNextOfSquare = getSquare.compose(getNextValue); long input = 10L; System.out.println("Input long value: " + input); System.out.println(); long squareOfNext = getSquareOfNext.applyAsLong(input); System.out.println("Square of next value: " + squareOfNext); System.out.println(); long nextOfSquare = getNextOfSquare.applyAsLong(input); System.out.println("Next to square of value: " + nextOfSquare); } }
输出
Input long value: 10 Getting square: 100 Getting Next value: 101 Square of next value: 101 Getting Next value: 11 Getting square: 121 Next to square of value: 121