Java Stream How to - Sort a collection with Lambda expression








Question

We would like to know how to sort a collection with Lambda expression.

Answer

/*from ww  w .  ja v  a 2s  .c  o m*/
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {

  public static void main(String[] args) throws Exception {
    // Lambda
    List<Person> persons = Arrays.asList(new Person("B", "V"),
        new Person("R", "K"));

    Collections.sort(persons, (Person a, Person b) -> {
      return b.firstName.compareTo(a.firstName);
    });
    Collections.sort(persons, (a, b) -> b.firstName.compareTo(a.firstName));
  }

}

/**
 * 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;
  }

}