About Me

My photo
Talk to me... you will know

Monday, August 29, 2011

sorting using comparator and comparable



People have problem in sorting class objects


here is a way to do that


have attached some code for example


i think its self explanatory



public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, String name, int age) {
        // set values on attributes
    }
    // getters & setters
}


*************************************************


import java.util.*;

public class Util {
  
    public static List<Employee> getEmployees() {
      
        List<Employee> col = new ArrayList<Employee>();
      
        col.add(new Employee(5, "Frank", 28));
        col.add(new Employee(1, "Jorge", 19));
        col.add(new Employee(6, "Bill", 34));
        col.add(new Employee(3, "Michel", 10));
        col.add(new Employee(7, "Simpson", 8));
        col.add(new Employee(4, "Clerk",16 ));
        col.add(new Employee(8, "Lee", 40));
        col.add(new Employee(2, "Mark", 30));
      
        return col;
    }
}

**********************************************

public class Employee implements Comparable<Employee> {
    private int empId;
    private String name;
    private int age;
  
    /**
     * Compare a given Employee with this object.
     * If employee id of this object is
     * greater than the received object,
     * then this object is greater than the other.
     */
    public int compareTo(Employee o) {
        return this.empId - o.empId ;
    }
    ….
}

************************************************************


import java.util.*;

public class TestEmployeeSort {
  
    public static void main(String[] args) {   
        List coll = Util.getEmployees();
        Collections.sort(coll); // sort method
        printList(coll);
    }
  
    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tName\tAge");
        for (Employee e: list) {
            System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
        }
    }
}








Here is another example... using your own custom sort method by implementing comparator and passing it along with your sort method

package compareExamples;

import java.io.*;
import java.util.*;
public class Laptop implements Comparable<Laptop> {

 // Implementing compareTo on custom objects!

 // Member elements
 String manufacturer;
 String color;
 String model;
 Laptop() {
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  
  try {
   System.out.print("Manufacturer: ");
   manufacturer = in.readLine();
   System.out.print("Model: ");
   model = in.readLine();
   System.out.println("Color: ");
   color = in.readLine();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 @Override
 public int compareTo(Laptop o) {
  String obj1_1 = manufacturer+" "+model+" "+color;
  String obj1_2 = manufacturer+" "+model;
  String obj2_1 = o.manufacturer+" "+o.model+" "+o.color;
  String obj2_2 = o.manufacturer+" "+o.model;
  if(manufacturer.equalsIgnoreCase(o.manufacturer)){
   if(model.equalsIgnoreCase(o.model)) {
    if(color.equalsIgnoreCase(o.color)) {
     return 0;
    }
    else
     return obj1_1.compareToIgnoreCase(obj2_1);
   }
   else 
    return obj1_2.compareToIgnoreCase(obj2_2);
   }
  else 
   return manufacturer.compareToIgnoreCase(o.manufacturer);
  
 }
 
 public static void main(String args[]) {
  Laptop a[] = new Laptop[5];
  for(int i=0;i<5;i++) {
   a[i] = new Laptop();
  }
  // Sorting with the help of the logic defined in compareTo method of the class Laptop
  Arrays.sort(a);
  for(Laptop b : a) {
   System.out.println(b.manufacturer+"\n"+b.model+"\n"+b.color+"\n\n");
  }
  
  System.out.println("********************************************");
  
  // Custom sorting with the help of the comparator defined in the class CompareLoptopByColor's compare method

  CompareLaptopByColor com = new CompareLaptopByColor();
  Arrays.sort(a,com);
  for(Laptop b : a) {
   System.out.println(b.manufacturer+"\n"+b.model+"\n"+b.color+"\n\n");
  }
 }
 
 
}

-------------------------- The custom comparator class-------------------------

package compareExamples;

import java.util.Comparator;

public class CompareLaptopByColor implements Comparator<Laptop> {

 @Override
 public int compare(Laptop arg0, Laptop arg1) {  
  return arg0.color.compareToIgnoreCase(arg1.color);
 }

}

No comments:

Post a Comment

There was an error in this gadget