Java 具有各种操作数的 lambda 表达式

Java lambda-expressions with miscellaneous operands

此 lambda 表达式非常适合具有两个操作数(a 和 b)的数学运算。

public class Math {
  interface IntegerMath {
    int operation(int a, int b);       
  }

  private static int apply(int a, int b, IntegerMath op) {
    return op.operation(a, b);
  }

  public static void main(String... args) {
    IntegerMath addition = (a, b) -> a + b;
    IntegerMath subtraction = (a, b) -> a - b;
    System.out.println("40 + 2 = " + apply(40, 2, addition));
    System.out.println("20 - 10 = " + apply(20, 10, subtraction));

  }
}

如何使用可能的 unary 操作来增强此 class,例如

IntergerMath square = (a) -> a * a;

?

你不能用 IntegerMath 来做,因为它是一个功能接口,其单个抽象方法接受两个 int 参数。您将需要一个用于一元操作的新界面。

顺便说一句,您不必自己定义这些接口。 java.util.function 包含您可以使用的接口,例如 IntUnaryOperatorIntBinaryOperator

你不能这样做,因为 square 方法没有相同的签名。

请注意,您也可以使用 IntBinaryOperatorIntUnaryOperator(您会注意到它们是完全独立的),而不是创建您自己的界面。

You'll need a new interface for unary operations.

public class Math {
  interface BinMath {
    int operation(int a, int b);

  }

  interface UnMath {
    int operation(int a);

  }

  private static int apply(int a, int b, BinMath op) {
    return op.operation(a, b);
  }

  private static int apply(int a, UnMath op) {
    return op.operation(a);
  }

  public static void main(String... args) {
    BinMath addition = (a, b) -> a + b;
    BinMath subtraction = (a, b) -> a - b;
    UnMath square = (a) -> a * a;

    System.out.println("40 + 2 = " + apply(40, 2, addition));
    System.out.println("20 - 10 = " + apply(20, 10, subtraction));
    System.out.println("20² = " + apply(20, square));

  }
}