Posts which you will also like.

Saturday, August 18, 2012

Java Tutorial:Sorting list using Comparator


In this java tutorial we are going to understand the sorting of a List with the help of Comparator interface.

So we will use sort(arrayToSort,Comparator) of Collections and Arrays to sort the list.Now we have to create a class which implements the comparator interface but before that we should have the class for which sorting is done.So lets create that first.

package com.techy.rajeev;

public class Employee{
    private String ename;
    private int eid;
    private double salary;

    public String getEname() {
        return ename;
    }

    public Employee(String ename, int eid, double salary) {
        super();
        this.ename = ename;
        this.eid = eid;
        this.salary = salary;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public int getEid() {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [ename=" + ename + ", eid=" + eid + ", salary="
                + salary + "]";
    }

}


Now lets create the Sorter class.


package com.techy.rajeev;

import java.util.Comparator;

public class SortByName implements Comparator<Employee> {

    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getEname().compareTo(o2.getEname());
    }

}


Now lets do the sorting


package com.techy.rajeev;

import java.util.*;

public class TestSorting {
    public static void main(String[] args) {
        ArrayList<Employee>al=new ArrayList<Employee>();
        al.add(new Employee("Anonymous",1,12345.00));
        al.add(new Employee("Hacker",2,32423));
        al.add(new Employee("Cba",3,23434));
        System.out.println("Before:"+al);
        SortByName sbn=new SortByName();
        Collections.sort(al,sbn);//passing the sorter to sort
        System.out.println("After:"+al);
        
    }

}

Output:

Before:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Hacker, eid=2, salary=32423.0], Employee [ename=Cba, eid=3, salary=23434.0]]

After:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Cba, eid=3, salary=23434.0], Employee [ename=Hacker, eid=2, salary=32423.0]]

Now I hope you know how to sort the list using comparator.Keep reading.Thumbs up

No comments:

Post a Comment

Your comment may wait for moderation....

DMCA.com Protected by Copyscape Online Plagiarism Tool