Saturday, December 28, 2019

How to Sort an ArrayList in Descending Order in Java

In Java ArrayList elements are added in sequential order and while iterating an arraylist same sequential order will be used to retrieve the elements. Sometimes you may have a requirement to sort an arraylist in ascending or descending order. In this post we'll see how to sort an ArrayList in descending order in Java.

Sorting ArrayList in descending order

For sorting ArrayList in descending order in Java there are two options

  1. Use method reverseOrder() provided by Collections class. See example.
  2. General form and description

    public static <T> Comparator<T> reverseOrder()
    
    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
  3. Using a custom comparator. See example.

You must also know about the overloaded method sort provided by the Collections class.

  • public static <T> void sort(List<T> list, Comparator<? super T> c) - Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).

Sorting ArrayList Using reverseOrder method

reverseOrder() method mentioned above can be provided as the second parameter in the sort method mentioned above and you will get the ArrayList sorted in reverse order. Let's see an example.

In the program Collections.reverseOrder() method is passed as an argument to the Collections.sort() method to sort ArrayList in reverse order.

public class SortListDemo {

    public static void main(String[] args) {
        // Using diamond operator (Right side no type specified)
        // Available from Java7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Chennai");
        cityList.add("Kolkata");
        cityList.add("Mumbai");
        // sorting the list in descending order
        Collections.sort(cityList, Collections.reverseOrder());
        //Displaying the list
        for(String city : cityList){
            System.out.println("Name " + city);
        }
    }
}

Output

Name Mumbai
Name Mumbai
Name Kolkata
Name Delhi
Name Chennai
Name Bangalore

Sorting Java ArrayList Using custom Comparator

Internally reverseOrder method calls a Comparator class to do the sorting in reverse order. You can do it yourself too by writing your own comparator class. Writing your own Comparator gives you more control over the object ordering.

public class SortListDemo {
    public static void main(String[] args) {
        // Using diamond operator (Right side no type specified)
        // Available from Java7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Chennai");
        cityList.add("Kolkata");
        cityList.add("Mumbai");
        // sorting the list in descending order
        Collections.sort(cityList, new MyComparator());
        //Displaying the list
        for(String city : cityList){
            System.out.println("Name " + city);
        }
    }
}

//Custom comparator class
class MyComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }    
}

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

That's all for this topic How to Sort an ArrayList in Descending Order in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Sort ArrayList of Custom Objects in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. How LinkedList Class Works Internally in Java
  5. CopyOnWriteArrayList in Java - The thread safe variant of ArrayList

You may also like-

  1. How does HashMap internally work in Java
  2. Difference Between CountDownLatch And CyclicBarrier in Java
  3. Phaser in Java concurrency
  4. varargs in Java
  5. What if run() method called directly instead of start() method
  6. static reference to the non-static method or field error
  7. Method overloading in Java
  8. Creating Custom Exception Class in Java