A comparator is an interface that is used to rearrange the ArrayList in a sorted manner. A comparator is used to sort an ArrayList of User-defined objects. In java, a Comparator is provided in java.util package. Using Comparator sort ArrayList on the basis of multiple variables, or simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator override the compare() method provided by the comparator interface.
Override the compare() method in such a way that it will reorder an ArrayList in descending order instead of ascending order. Change only in the comparison part for descending order. See the difference between both compare() functions.
Ascending Order public int compare(Item i1, Item i2) { if (i1.Property== i2.Property) return 0; else if (i1.Property > i2.Property) return 1; else return -1; } Descending Order public int compare(Item i1, Item i2) { if (i1.Property== i2.Property) return 0; else if (i1.Property < i2.Property) return 1; else return -1; }
If there is any need to reorder an ArrayList on the basis of the variable of string type like name, etc. rewrite the compare() function Like below.
Ascending Order public int compare(Shop s1, Shop s2) { return s1.name.compareTo(s2.name); } Descending Order public int compare(Shop s1, Shop s2) { return s2.name.compareTo(s1.name); }
Example:
Java
// Java Program to sort the ArrayList // in descending order using comparator import java.util.*; // create the Laptop class class Laptop { int ModalNo; String name; int ram; Laptop( int ModalNo, String name, int ram) { this .ModalNo = ModalNo; this .name = name; this .ram = ram; } } // creates the comparator for comparing RAM class RamComparator implements Comparator<Laptop> { // override the compare() method public int compare(Laptop l1, Laptop l2) { if (l1.ram == l2.ram) { return 0 ; } else if (l1.ram < l2.ram) { return 1 ; } else { return - 1 ; } } } class GFG { public static void main(String[] args) { // create the ArrayList object ArrayList<Laptop> l = new ArrayList<Laptop>(); l.add( new Laptop( 322 , "Dell" , 2 )); l.add( new Laptop( 342 , "Asus" , 8 )); l.add( new Laptop( 821 , "HP" , 16 )); l.add( new Laptop( 251 , "Lenovo" , 6 )); l.add( new Laptop( 572 , "Acer" , 4 )); System.out.println( "before sorting" ); System.out.println( "Ram" + " " + "Name" + " " + "ModalNo" ); for (Laptop laptop : l) { System.out.println(laptop.ram + " " + laptop.name + " " + laptop.ModalNo); } System.out.println(); System.out.println( "After sorting(sorted by Ram)" ); System.out.println( "Ram" + " " + "Name" + " " + "ModalNo" ); // call the sort function Collections.sort(l, new RamComparator()); for (Laptop laptop : l) { System.out.println(laptop.ram + " " + laptop.name + " " + laptop.ModalNo); } } } |
before sorting Ram Name ModalNo 2 Dell 322 8 Asus 342 16 HP 821 6 Lenovo 251 4 Acer 572 After sorting(sorted by Ram) Ram Name ModalNo 16 HP 821 8 Asus 342 6 Lenovo 251 4 Acer 572 2 Dell 322