如何使用 lambda 表示式在 Java 中實現 IntBinaryOperator?


IntBinaryOperator 是 Java 8 中java.util.function 包中的函式介面。此介面期望接受兩個型別為 int 的引數作為輸入,並生成一個int 型別的結果。IntBinaryOperator 可用作lambda 表示式方法 引用的賦值目標。它僅包含一個抽象方法:applyAsInt()

語法

@FunctionalInterface
public interface IntBinaryOperator {
 int applyAsInt(int left, int right)
}

示例

import java.util.function.*;
public class IntBinaryOperatorTest {
   public static void main(String[] args) {
      IntBinaryOperator test1 = (a, b) -> a + b; // lambda expression
      System.out.println("Addition of two parameters: " + test1.applyAsInt(10, 20));
      IntFunction test2 = new IntFunction() {
         @Override
         public IntBinaryOperator apply(int value) {
            return new IntBinaryOperator() {
               @Override
               public int applyAsInt(int left, int right) {
                  return value * left * right;
               }
            };
         }
      };
      System.out.println("Multiplication of three parameters: " + test2.apply(10).applyAsInt(20, 30));
   }
}

輸出

Addition of two parameters: 30
Multiplication of three parameters: 6000

更新於: 14-7-2020

331 次瀏覽

開啟您職業生涯

完成課程認證

開始吧
廣告
© . All rights reserved.