【问题标题】:Java lambda-expressions with miscellaneous operands带有各种操作数的 Java lambda 表达式
【发布时间】:2015-11-11 13:12:06
【问题描述】:

这个 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));

  }
}

如何通过可能的一元操作来增强这个类,例如

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

?

【问题讨论】:

    标签: java lambda interface java-8 operator-overloading


    【解决方案1】:

    IntegerMath 无法做到这一点,因为它是一个函数式接口,其单个抽象方法需要两个 int 参数。你需要一个新的接口来进行一元操作。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        你需要一个新的接口来进行一元操作。

        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));
        
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2010-11-11
          • 2014-03-25
          • 2013-07-02
          • 1970-01-01
          • 2020-10-06
          • 2016-07-27
          • 2014-08-17
          • 2017-06-02
          • 1970-01-01
          相关资源
          最近更新 更多