如何在 Java 中将比较器写成 lambda 表达式?


Lambda 表达式匿名方法,在 Java 中不单独执行。相反,它用于实现由函数式接口定义的方法。任何函数式接口和Comparator都可以使用 Lambda 表达式,Comparator是函数式接口。使用Comparator接口时,在比较对象集合时会进行比较。

在以下示例中,我们可以使用Comparator接口通过名称对员工列表进行排序。

示例

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Employee {
   int id;
   String name;
   double salary;
   public Employee(int id, String name, double salary) {
      super();
      this.id = id;
      this.name = name;
      this.salary = salary;
   }
}
public class LambdaComparatorTest {
   public static void main(String[] args) {
      List<Employee> list = new ArrayList<Employee>();

      // Adding employees
      list.add(new Employee(115, "Adithya", 25000.00));
      list.add(new Employee(125, "Jai", 30000.00));
      list.add(new Employee(135, "Chaitanya", 40000.00));
      System.out.println("Sorting the employee list based on the name");

      // implementing lambda expression
      Collections.sort(list, (p1, p2) -> {
         return p1.name.compareTo(p2.name); 
      }); 
      for(Employee e : list) {
         System.out.println(e.id + " " + e.name + " " + e.salary);
      }
   }
}

输出

Sorting the employee list based on the name
115 Adithya 25000.0
135 Chaitanya 40000.0
125 Jai 30000.0

更新于: 2019-12-06

4K+ 浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.