javacodex.com
Java Examples
Java Examples
memu home questions

Sort An ArrayList Using A Comparator

This java example shows you how to sort an ArrayList using a Comparator.

Source: (ArrayListSort.java)

import java.util.*;
 
public class ArrayListSort { 
   public static void main(String[] args) { 
      ArrayList<Employee> list = new ArrayList<Employee>();
      list.add(new Employee("Tom", 222));
      list.add(new Employee("Pat", 111));
      list.add(new Employee("Jim", 444));
      list.add(new Employee("Tim", 333));
      Collections.sort(list, new EmployeeComparator());
      for(Employee e: list) {
         System.out.println( e.getName() + " " + e.getNumber());
      }
   } 
}
 
class EmployeeComparator implements Comparator<Employee> {
   public int compare(Employee e1, Employee e2) {
      return ((e1.getNumber() > e2.getNumber()) ? 1 : -1);
   }
}
 
class Employee {
   String name;
   int number;
 
   Employee(String name, int number) {
        this.name = name;
        this.number = number;
   }
 
   String getName() { return name; }
   int getNumber() { return number; }
}
 

Output:

# java ArrayListSort 
Pat 111
Tom 222
Tim 333
Jim 444

Contact: javacodex@yahoo.com