Java Stream How to - Create Comparator from Lambda








Question

We would like to know how to create Comparator from Lambda.

Answer

//from w  w w.j a va  2s. c  o m
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;
  }
}

The code above generates the following result.