How to Sort a Collection in Java



Consider a list of Person object. There are two ways to sort the list . Using Comparator or Comparable. 

class Person implements Comparable{
  public String name;
  public String lastName;
 
  public Person(String name, String lastName){
     this.name=name;
     this.lastName=lastName;
  }
  public String getName(){
    return name;
  }
  public String getLastName(){
    return lastName;
  }
 
  public int compareTo(Object obj){
    Person p = (Person)obj;
    return this.name.compareTo(p.getName);
  }
  public static void main(String arg[]){
        List myList = new ArrayList();
 
    myList.add(new Person("Robert","USA"));
    myList.add(new Person("Andy","UK"));
    myList.add(new Person("Harish","India"));
    Collections.sort(myList);
    for(Person person : myList){
     System.out.println("My name is "+person.getName());
    }
  }
 }
  Output is :
  My name is Andy
  My name is Harish
  My name is Robert


public sortList()  {
 
     List personList = getListofPerson(); // some method to get the list.
     //sort by name;
   Collections.sort(personList, new Comparator() {
           public int compare(Person e1, Person e2) {
               return e2.name.compareTo(e1.name);
         }});
   // sort by age
     
     Collections.sort(personList, new Comparator() {
           public int compare(Person e1, Person e2) {
                if (e1.age > e2.age )
                return 1;
                if (e1.age < e2.age)
                 return -1;
                else
                    return 0;
         }});
 }

0 comments: