This program will sort in descending order.
import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class SortArray3
{
static public void main(String...alt)
{
String[] s={"zoo","apple","cat","banana","lock"};
out.println("Before Sorting : ");
for(String x:s)
out.print(x+" ");
out.println("\n\nAfter Sorting : ");
Arrays.sort(s,new MyComparator()); // public static void sort(java.lang.Object[])
for(String x:s)
out.print(x+" ");
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
return s2.compareTo(s1); // compareTo(String s) available in String class
// s2.compareTo(s1)--> Descending Order
// s1.compareTo(s2)--> Ascending Order
}
}
import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class SortArray3
{
static public void main(String...alt)
{
String[] s={"zoo","apple","cat","banana","lock"};
out.println("Before Sorting : ");
for(String x:s)
out.print(x+" ");
out.println("\n\nAfter Sorting : ");
Arrays.sort(s,new MyComparator()); // public static void sort(java.lang.Object[])
for(String x:s)
out.print(x+" ");
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
return s2.compareTo(s1); // compareTo(String s) available in String class
// s2.compareTo(s1)--> Descending Order
// s1.compareTo(s2)--> Ascending Order
}
}
0 Comment to "Java Program to sort Object/String class elements with customized sorting order."
Post a Comment