Java ArrayList Sorting -2.1

This is part two of Java ArrayList sorting-2

In the previous post we learned how to sort an ArrayList using comparable interface .

# Sort an Array List using comparator interface :
First create a comaparator class:
Then to sort the Array List use:
Collections.sort(students,new cgpaSorted());

Without creating class , using anonymous class :
Extra :

#Ascending sort : 
public int compare(Student obj1, Student obj2) {
     return Double.compare(obj1.cgpa, obj2.cgpa); // Ascending sort
}
Here first parameter of compare method is Student obj1 and first parameter of Double.compare() is also obj1 , again second parameter of both is obj2. The ordering of the parameter is same in case of Ascending sort.

#Descending sort:

The ordering of the parameter is not same in case of Descending sort.
public int compare(Student obj1, Student obj2) {
       return Double.compare(obj2.cgpa, obj1.cgpa); // Descending sort
}
Here first parameter of compare method is Student obj1 and first parameter of Double.compare() is obj2 , again second parameter of compare method is Student obj2 and second parameter of Double.compare() is obj1.

~Integer Compare method : 
Integer.compare(int_variable1, int variable2);
~String Compare method :
String_Variable1_Name.compareTo(String_Variable2_Name);

Comments

Popular Posts