如何在 Java 中使用 Lambda 来实现 LongUnaryOperator?


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

更新日期:2020 年 7 月 14 日

163 次浏览

开启您的职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.