App下載
首頁javalambda_apiJava Stream - 如何從Lambda創(chuàng)建比較器

Java Stream - 如何從Lambda創(chuàng)建比較器

我們想知道如何從Lambda創(chuàng)建比較器。
import java.util.Comparator;

public class Main {
  public static void main(String... args) {
    // Comparators
    Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);

    Person p1 = new Person("A", "Z");
    Person p2 = new Person("B", "Z");

    System.out.println(comparator.compare(p1, p2));// > 0
    System.out.println(comparator.reversed().compare(p1, p2));  // < 0

  }
}
class Person {
  String firstName;
  String lastName;

  Person() {}

  Person(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
  }
}