Sorting a Collection containing user defined Objects : Collections Sort « Collections « Java Tutorial






import java.util.Arrays;

class Person implements Comparable<Person> {
  public Person(String firstName, String surname) {
    this.firstName = firstName;
    this.surname = surname;
  }
  public String toString() {
    return firstName + " " + surname;
  }
  public int compareTo(Person person) {
    int result = surname.compareTo(person.surname);
    return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;
  }
  private String firstName;
  private String surname;
}
public class MainClass {
  public static void main(String[] args) {
    Person[] authors = { new Person("A", "B"), 
                         new Person("C", "D"),
                         new Person("E", "F"), 
                         new Person("Z", "Y"),
                         new Person("X", "T"), 
                         new Person("O", "R") };
    Arrays.sort(authors);
    System.out.println("\nThe cast is ascending sequence is:\n");
    for (Person person : authors) {
      System.out.println(person);
    }
  }
}
The cast is ascending sequence is:
  A B
  C D
  E F
  O R
  X T
  Z Y








9.42.Collections Sort
9.42.1.Sorting a List
9.42.2.Reversing Order
9.42.3.Sorting a Collection containing user defined Objects
9.42.4.Keeping upper and lowercase letters together