Skip to content

Instantly share code, notes, and snippets.

@pbesra
Created January 2, 2017 20:15
Show Gist options
  • Save pbesra/821655609fc31c0f89153acbd9e57781 to your computer and use it in GitHub Desktop.
Save pbesra/821655609fc31c0f89153acbd9e57781 to your computer and use it in GitHub Desktop.
Example of Comparable and Comparator interface and how they work
//Package removed
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
class Test{
public static void main(String[] args) {
//list to store people objects
List<Person> people=new ArrayList<Person>();
people.add(new Person("prakash", 21, 1200000));
people.add(new Person("harry", 22, 900000));
people.add(new Person("mohit", 28, 1800000));
people.add(new Person("rahul", 24, 4000000));
Collections.sort(people);
for(Person p : people){
System.out.println(p.name+" "+p.age+" "+p.salary);
}
System.out.println("-----------using comparator------------");
System.out.println("using age : ");
setAge ageOrder=new setAge();
Collections.sort(people, ageOrder);
for(Person p : people){
System.out.println(p.name+" "+p.age+" "+p.salary);
}
System.out.println("using name : ");
setName nameOrder=new setName();
Collections.sort(people, nameOrder);
for(Person p : people){
System.out.println(p.name+" "+p.age+" "+p.salary);
}
System.out.println("using salary : ");
setSalary salaryOrder=new setSalary();
Collections.sort(people, salaryOrder);
for(Person p : people){
System.out.println(p.name+" "+p.age+" "+p.salary);
}
}
}
class Person implements Comparable<Person>{
public String name;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getSalary() {
return salary;
}
public int age;
public int salary;
public Person(String nm, int ag, int sal){
this.name=nm;
this.age=ag;
this.salary=sal;
}
public int compareTo(Person o) {
return (this.salary-o.salary);
}
}
class setAge implements Comparator<Person>{
public int compare(Person o1, Person o2) {
if(o1.getAge()>o2.getAge()){
return 1;
}
else if(o1.getAge()<o2.getAge()){
return -1;
}
return 0;
}
}
class setSalary implements Comparator<Person>{
public int compare(Person o1, Person o2) {
if(o1.getSalary()>o2.getSalary()){
return 1;
}
else if(o1.getSalary()<o2.getSalary()){
return -1;
}
return 0;
}
}
class setName implements Comparator<Person>{
public int compare(Person o1, Person o2) {
return (o1.getName().compareTo(o2.getName()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment