Java Collection How to - Sort TreeMaps or ArrayLists with Person objects based on their ID, name, or birthdate








Question

We would like to know how to sort TreeMaps or ArrayLists with Person objects based on their ID, name, or birthdate.

Answer

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
//  www  .j  a v  a 2 s .c o m
public class Main {

  public static void main(String[] args) {
    List<Person> list = new ArrayList<Person>();
    for (int i = 10; i > 0; i--) {
      list.add(new Person(i, "name" + String.valueOf(i), new Date()));
    }
    System.out.println(list);
    Collections.sort(list);
    System.out.println(list);
  }
}

class Person implements Comparable<Person> {
  public final String name;
  public final int id;
  public final Date birthdate;

  public Person(int id, String name, Date birthdate) {
    this.id = id;
    this.name = name;
    this.birthdate = birthdate;
  }

  @Override
  public boolean equals(Object other) {
    if (!(other instanceof Person)) {
      return false;
    }
    return this.id == ((Person) other).id;
  }

  @Override
  public int hashCode() {
    return 41 * id;
  }

  @Override
  public String toString() {
    return "Person<" + id + ">";
  }

  @Override
  public int compareTo(Person other) {
    if (!(other instanceof Person)) {
      throw new IllegalArgumentException();
    }
    return this.id - ((Person) other).id;
  }
}

The code above generates the following result.