Wednesday, November 19, 2014

CustomComparator in java

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

public class SecondArray {
 public static ArrayList list = new ArrayList();
 public static void main(String args[]){
  CustomString cs= new CustomString("123744444");
  list.add(cs);
  cs= new CustomString("421212345");
  list.add(cs);
  cs= new CustomString("758312948");
  list.add(cs);
  cs= new CustomString("134129302");
  list.add(cs);
  cs= new CustomString("123755555");
  list.add(cs);
  
  System.out.println(list);
  
  
  Collections.sort(list, new CustomComparator());
  
  System.out.println(list);
  
 }
 
}
class CustomString {
 
 String [] devidedValues = new String[2];
 
 CustomString(String value){
  devidedValues[0] = value.substring(0, 4);
  devidedValues[1] = value.substring(4, value.length());
  
 }

 /**
  * @return the devidedValues
  */
 public String[] getDevidedValues() {
  return devidedValues;
 }

 /**
  * @param devidedValues the devidedValues to set
  */
 public void setDevidedValues(String[] devidedValues) {
  this.devidedValues = devidedValues;
 }

 /* (non-Javadoc)
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
  return devidedValues[0] + devidedValues[1];
 }
 
}

class CustomComparator implements Comparator {

 @Override
 public int compare(CustomString arg0, CustomString arg1) {
  String[] first = arg0.getDevidedValues();
  String[] second = arg1.getDevidedValues();
  
  int firstCompareVal = first[0].compareTo(second[0]) ;
  
  if(first[0].compareTo(second[0]) == 0){
   return first[1].compareTo(second[1]) * -1; 
  }else{
   return firstCompareVal;
  }
 }

}

No comments:

Post a Comment