Java Collection How to - Sort ArrayList of custom Objects by property








Question

We would like to know how to sort ArrayList of custom Objects by property.

Answer

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
//from   w  w  w. j  ava 2 s. c  o m
class Person {
  public String name;
  public int id;
  public Date hireDate;

  public Person(String iname, int iid, Date ihireDate) {
    name = iname;
    id = iid;
    hireDate = ihireDate;
  }

  public String toString() {
    return name + " " + id + " " + hireDate.toString();
  }

}

// Comparator
class CompId implements Comparator<Person> {
  @Override
  public int compare(Person arg0, Person arg1) {
    return arg0.id - arg1.id;
  }
}

class CompDate implements Comparator<Person> {
  private int mod = 1;

  public CompDate(boolean desc) {
    if (desc)
      mod = -1;
  }

  @Override
  public int compare(Person arg0, Person arg1) {
    return mod * arg0.hireDate.compareTo(arg1.hireDate);
  }
}

public class Main {
  public static void main(String[] args) {
    SimpleDateFormat df = new SimpleDateFormat("mm-dd-yyyy");
    ArrayList<Person> people;
    people = new ArrayList<Person>();
    try {
      people.add(new Person("A", 9, df.parse("12-12-2014")));
      people.add(new Person("B", 2, df.parse("1-12-2013")));
      people.add(new Person("C", 4, df.parse("12-2-2012")));
    } catch (ParseException e) {
      e.printStackTrace();
    }

    Collections.sort(people, new CompId());
    System.out.println("BY ID");
    for (Person p : people) {
      System.out.println(p.toString());
    }

    Collections.sort(people, new CompDate(false));
    System.out.println("BY Date asc");
    for (Person p : people) {
      System.out.println(p.toString());
    }
    Collections.sort(people, new CompDate(true));
    System.out.println("BY Date desc");
    for (Person p : people) {
      System.out.println(p.toString());
    }

  }

}

The code above generates the following result.