Sunday, July 20, 2014

Comparator Interface example in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;


  class Mobile {
 
 private int cameraMegaPixel;
 private int batteryLifeInHours;
 private String brandName;
 
 Mobile(String BrandName, int cameraMP, int batteryHours) {
   
  this.brandName = BrandName;
  this.cameraMegaPixel = cameraMP;
  this.batteryLifeInHours = batteryHours;
 }
 
 public int getbatteryHours() {
  return batteryLifeInHours;
 }
 
 
 
 public String getBrandName() {
  return brandName;
 }
 
 public int getCameraMP() {
 return cameraMegaPixel;
}
 
 public String toString()
 {
String str =  brandName +  " \t " + batteryLifeInHours + "\t  " + cameraMegaPixel;

return str;
 }
 
}


class SortMobileByMP implements Comparator {  

public int compare(Mobile mob1, Mobile mob2) {

int result =0;
if (mob1.getCameraMP() < mob2.getCameraMP())
result =-1;
else if (mob1.getCameraMP() > mob2.getCameraMP())
result = 1;
else
result =0;

return result;
}
}

  class SortMobileByBatteryLife implements Comparator {  


public int compare(Mobile mob1, Mobile mob2) {

int result =0;
if (mob1.getbatteryHours() < mob2.getbatteryHours())
result =-1;
else if (mob1.getbatteryHours() > mob2.getbatteryHours())
result = 1;
else
result =0;

return result;
}
 

}

public class ComparatorExample_mobile {

/**
* @param args
*/
public static void main(String[] args) {
compareExample();


}

public static void compareExample()
{


 ArrayList mobileList = new ArrayList(
  Arrays.asList(
                                                                       new Mobile("Samsung S5",5,12),
  new Mobile("IPhone 5c",8,14),
  new Mobile("HTC touch",6,10),
  new Mobile("Nokia Lumia",12,18)   )
  );

 System.out.println("Mobile Phone list befor sorting :");

 System.out.println("Name   \t Battery Life (hours) Camera (MP)");

 for (int i = 0; i < mobileList.size(); i++) {
  System.out.println(mobileList.get(i));
 }

 Collections.sort(mobileList, new SortMobileByMP());

 System.out.println("Mobile Phone list after sorting :(by camera MP)");
 System.out.println("Name   \t Battery Life (hours) Camera (MP)");
 for (int i = 0; i < mobileList.size(); i++) {
  System.out.println(mobileList.get(i));
 
 }
 
  System.out.println("Mobile Phone list befor sorting :");

System.out.println("Name   \t Battery Life (hours) Camera (MP)");

 for (int  i = 0; i < mobileList.size(); i++) {
 System.out.println(mobileList.get(i));
 }

 Collections.sort(mobileList, new SortMobileByBatteryLife());

       System.out.println("Mobile Phone list after sorting :(by Battery Life)");

               System.out.println("Name   \t Battery Life (hours) Camera (MP)");
 for (int  i = 0; i < mobileList.size(); i++) {
   System.out.println(mobileList.get(i));
 }

}
}

No comments: