Java中使用Lambda表达式实现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 表达式
      System.out.println("两个参数相加: " + 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("三个参数相乘: " + test2.apply(10).applyAsInt(20, 30));
   }
}

输出结果

两个参数相加: 30
三个参数相乘: 6000