Tuesday 2 April 2013

Use of Comparator class for sorting ArrayList Objects

// ---------- Use of Comparator class for sorting ArrayList ------------ //

import java.util.*;

public class SortByComparator {
  Integer empcode;
  String name;
public SortByComparator(){
empcode = 1001;
name = "chetan";
}
public SortByComparator(int empcode, String name ){
this.empcode = empcode;
this.name = name;
}
public String toString(){
return "Emp code is:"+empcode+"Emp name is:"+name;
}
}

class  SortByName implements Comparator <SortByComparator>{
      public int compare(SortByComparator o1, SortByComparator o2){
      return o1.name.compareToIgnoreCase(o2.name);
      }
}
class SortByEmpCode implements Comparator <SortByComparator>{
public int compare(SortByComparator o1, SortByComparator o2){
return o1.empcode.compareTo(o2.empcode);
}
}

class SortRun{
public static void main(String args[]){
List <SortByComparator> l = new ArrayList <SortByComparator>();
l.add(new SortByComparator());
l.add(new SortByComparator(9002,"Brijaes"));
l.add(new SortByComparator(2004,"kapil"));
l.add(new SortByComparator(1005,"Aman Kumar"));
l.add(new SortByComparator(2001,"suraj"));
System.out.println("\nBefore Sorting:"+l);
Collections.sort(l, new SortByName());
//Collections.sort(l, new SortByEmpCode());
System.out.println("\nAfter sorting:"+l);
}
}

// Sorting of Srting and Integer Arraylist use of Comparator Interface 

package TestCollection;
import java.util.*;

public class Sample1 {

public static void main(String args[]){

List <Integer> list = new ArrayList <Integer>();
list.add(10);
list.add(200);
list.add(50);
list.add(26);
list.add(15);
list.add(80);
list.add(40);
list.add(30); 

List <String> list1 = new ArrayList <String> ();

list1.add("Deepak");
list1.add("manoj");
list1.add("Aman");
list1.add("vijay");
list1.add("Brijesh");
list1.add("Amit");
list1.add("chetan");

Collections.sort(list,new MyIntComparable());
for(Integer integer : list){
System.out.println(integer);


Collections.sort(list1, new MyStringComparable());
for(String string : list1){
System.out.println(string);
}
}
}

class MyIntComparable implements Comparator <Integer>{

public int compare(Integer o1, Integer o2){

return (o1<o2 ? -1 : (o1==o2 ? 0 : 1));

}
class MyStringComparable implements Comparator <String>{
public int compare(String s1, String s2){
return s1.compareToIgnoreCase(s2);
//return (s1<s2 ? -1 : (s1==s2 ? 0 : 1));

}



No comments:

Post a Comment