Wednesday, September 11, 2013

How many ways to sort an ArrayList or Collection ?


Ways to Sort ArrayList or Collection :

There are different ways to sort ArrayList

1) Sort using Arrays class  as below.

  Arrays.sort(array, arrayComparator);
  Arrays.sort(arrayList, arrayListComparator);


2) Sort using Collections class as below.
  
  Collections.sort(arrayList, arrayListComparator);

similarly.. to Sort an ArrayList of Book objects..

   Collections.sort(books, new Comparator<Book>(){//anonymous class
        public int compare(Book b1, Book b2) {
            return if b1 >b2 return +1 , if b2>b1 return -1, otherwise 0;    //pseudo code
        }
}//end method

3) Sort using Comparable Interface.
   If we want to sort ArrayList without the need of Comparator then implement Elements of ArrayList object to Comparable interface, And override compareTo() method based on our requirement.

ex: 


public class Employee implements Comparable<Employee> {
    private int id;
    private String name;
    private int age;
    private long salary;
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    public long getSalary() {
        return salary;
    }
    public Employee(int id, String name, int age, int salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    @Override
    public int compareTo(Employee emp) {
        return (this.id - emp.id);
    }
    @Override
    public String toString() {
        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                this.salary + "]";
    }
}// end class


usage:


//sorting custom object array
Employee[] empArr = new Employee[4];
empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);
//
Arrays.sort(empArr);
System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));
//


When to use Comparable and Comparator:

Comparable: 
      Use this Interface when, An Element in any collection object can be compared at any time. 

 It means , If you write your Employee class by implementing Comparable interface, You are suppose to sort any collection object at any time in the future.

So, simple we can say that implements Comparable interface is used before placing any Element in Collection object.


Comparator: 
     Use this Interface when, you want to sort collection at runtime.

It means, Suppose you don't know how to sort Elements in Collection object and want to sort at runtime based on the requirement.

  ex:  Suppose you have an ArrayList object of elements of type Employee and want to sort that ArrayList object based on employee id for the first time, then sort based on employee name, and then sort based on employee salary... like this way you want to sort at run time.
   
  
For this, you have to write a custom class which implements Comparator interface and override compare() method and write the logic based on the requirement like, sort based on id , name , salary..etc.


public class EmployeeIdSortComparator implements Comparator<Employee>{

     public int  compare(Employee e1, Employee e2){
              //write logic to sort based on the requirement.
    }
    // also override equals(Object o) method to compare..

   }// end class

So, simply we can say that implements Comparable is used after placing any Element in Collection object also. It is runtime comparison. 

4)  Write your own logic to sort collection object like how we sort an array of integers ( bubble, heap, insertion,..etc)..

This is at your own risk.

Please let me know if any mistakes are here in the current post. please give your feedback at nagarjuna.lingala@gmail.com


sources:

No comments:

Post a Comment