Friday, March 6, 2009

collections class sort



package myutil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class MycComparator implements Comparator {
public int compare(Object o1,Object o2 ) {
String s1=(String)o1;
String s2=(String)o2;
return s2.compareTo(s1);
}
}
public class CollectionsSort {
public static void main(String [] args ) {
List l=new ArrayList();
l.add("Z");
l.add("A");
l.add("H");
l.add("E");
l.add("O");
l.add("B");
l.add("F");
l.add("Y");
System.out.println("The List Before Sorting"+l);
Collections.sort(l);
System.out.println("The List After Sorting asending order"+l);
// using comparator
Collections.sort(l,new MycComparator());
System.out.println("The List After Sorting dsending order"+l);

}
}

output:
The List Before Sorting[Z, A, H, E, O, B, F, Y]
The List After Sorting asending order[A, B, E, F, H, O, Y, Z]
The List After Sorting dsending order[Z, Y, O, H, F, E, B, A]



0 comments:

Post a Comment