Sunday, 4 October 2015

OBJECT SORTING IN JAVA COMPARATOR VS COMPARABLE

comparable and comparators are two interfaces provided by java to Sort custom Objects . Here i'm going to explain to you how to sort a person class using java


package sample;
import  com.solo.Adress;public class Person implements Comparable<Person> {

    private String name;    private String age;    private Adress adress;
    public String getName() {
        return name;    }

    public void setName(String name) {
        this.name = name;    }


    public String getAge() {
        return age;    }

    public Adress getAdress() {
        return adress;    }

    public void setAdress(Adress adress) {
        this.adress = adress;    }

    public void setAge(String age) {
        this.age = age;    }


    public Person(String name, String age, Adress adress) {
        this.name = name;        this.age = age;        this.adress = adress;    }


    @Override

    public int compareTo(Person person) {
        return this.name.compareTo(person.getName());    }
}

THis is a simple example for comparable interface it is self explanatory .it has one method

very simple and used for normal sorting operations 


what if you want more than two sorting techniques i.e you want to sort by both age and salry 

that's where comparator kicks in
 
package sample;
import java.util.Comparator;
public class Agecomparator implements Comparator<Person> {
    @Override    public int compare(Person person, Person t1) {
        return person.getAge().compareTo(t1.getAge());    }
}

System.out.println("before Sorting");printperson(personList);
System.out.println("....................sorting........................");
Collections.sort(personList,new  Agecomparator());
System.out.println("....................... After sorting --------------------------");
printperson(personList);


before Sorting
solomon
anish
bob
zolton
farage
hercules
....................sorting........................
....................... After sorting --------------------------
farage
hercules
zolton
anish
solomon
bob




No comments:

Post a Comment