Java Stream How to - Create Lambda expression and use it later








Question

We would like to know how to create Lambda expression and use it later.

Answer

/*  w w  w  .j  ava 2  s  .  c o m*/
import java.io.PrintStream;
import java.util.Comparator;

public class Main {

  public static void main(String[] args) throws Exception {
    Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
    Person p1 = new Person("John", "Doe");
    Person p2 = new Person("Alice", "Wonderland");
    comparator.compare(p1, p2);             // > 0
    comparator.reversed().compare(p1, p2); // <0
  }

}

/**
 * Simple person object with first and last name.
 */
class Person implements Cloneable {

  String firstName = null;
  String lastName = null;

  // constructors

  public Person() {
  }

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

  // Person methods

  public void println(PrintStream out) {
    out.println(this.toString());
  }

  public int compareToLastNameThenFirstName(Person p) {
    int result = 0;
    result = this.getLastName().compareTo(p.getLastName());
    if (result == 0) {
      result = this.getFirstName().compareTo(p.getFirstName());
    }
    return result;
  }

  // implement Cloneable methods

  @Override
  public Person clone() {
    Person cloneOf = new Person(firstName, lastName);
    return cloneOf;
  }

  // implement Object methods

  public boolean equals(Person p) {
    if (this.firstName.equals(p.getFirstName()))
      return false;
    if (this.lastName.equals(p.getLastName()))
      return false;
    return true;
  }

  @Override
  public String toString() {
    return "(" + firstName + " " + lastName + ")";
  }

  // getters and setters

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

}