代码之家  ›  专栏  ›  技术社区  ›  Sahand

lambda函数如何成为comparator的compare()方法

  •  4
  • Sahand  · 技术社区  · 7 年前

    我已经看到,在Java 8中,可以定义这样的比较器:

    Comparator c = (Computer c1, Computer c2) -> c1.getAge().compareTo(c2.getAge());
    

    相当于:

    Comparator d = new Comparator<Computer> () {
        @Override
        public int compare(Computer c1, Computer c2){
            return c1.getAge().compareTo(c2.getAge());
        }
    };
    

    我想知道这是怎么回事。在第二个例子中,它相当简单:a Comparator 对象是用方法创建的 compare 通过使用 compareTo 方法在 age 性质 Computer . 当我们执行以下操作时,我们只需调用此方法:

    Computer comp1 = new Computer(10);
    Computer comp2 = new Computer(11);
    d.compare(comp1, comp2); // -1
    

    但是在第一个例子中,当使用lambda时发生了什么?在我看来,我们正在设置 比较器 等于执行比较的方法。但这不可能,因为 比较器 对象是具有方法的对象 比较 . 我已经了解到lambda可以与函数接口(只有一个方法的接口)一起使用。但是 比较器 不是功能接口(它有许多其他方法,而不是 比较 !)那么Java解释器如何知道它是 比较 我们正在实施的方法?

    2 回复  |  直到 7 年前
        1
  •  6
  •   Zabuzard Louis-Philippe Lebouthillier    7 年前

    解释

    Comparator 是一个 功能接口 (只需要一种方法)。因此,可以使用lambda表达式创建它的实例。

    它的行为与其他创建实例的方法非常相似,例如扩展的常规类或匿名类。

    lambda引用函数接口所需的一个方法。因为只有一个方法,所以它不模棱两可。lambda 姓名 输入参数,然后给出方法的实现(它提供 身体 )


    概述

    您可以创建以下选项 实例 接口或抽象类:

    1. 创建一个扩展并使用new的类
    2. 使用匿名类

    假设我们有一个只提供 一种方法 (它叫 功能接口 然后),我们还有以下两个选项来创建它的实例:

    1. 使用lambda表达式
    2. 使用方法引用

    例如,我们希望使用以下接口创建一个乘法实例:

    @FunctionalInterface
    public interface Operation {
        int op(int a, int b);
    }
    
    1. 创建一个扩展并使用新的类:

      public class Multiplicator implements Operation {
          @Override
          public int op(int a, int b) {
              return a * b;
          }
      }
      
      // Usage
      Operation operation = new Multiplicator();
      System.out.println(operation.op(5, 2)); // 10
      
    2. 使用匿名类:

      Operation operation = new Operation() {
          @Override
          public int op(int a, int b) {
              return a * b;
          }
      };
      
      // Usage
      System.out.println(operation.op(5, 2)); // 10
      
    3. 使用lambda表达式:

      Operation operation = (a, b) -> a * b;
      System.out.println(operation.op(5, 2)); // 10
      
    4. 使用方法引用:

      // Somewhere else in our project, in the `MathUtil` class
      public static int multiply(int a, int b) {
          return a * b;
      }
      
      // Usage
      Operation operation = MathUtil::multiply;
      System.out.println(operation.op(5, 2)); // 10
      
        2
  •  3
  •   isnot2bad    7 年前

    技术上, java.util.Comparator 是一个函数接口,不仅因为它被注释为一个,而且因为它只有一个(抽象)方法, compare(T, T) .

    所有其他方法都有默认实现,因此考虑到lambda表达式,将忽略这些方法。

    也见 Precise definition of "functional interface" in Java 8