Tuesday, January 2, 2024

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 following 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.

    There is also a Comparator.reverseOrder() method Java 8 onward that can also be used.

  3. Using a custom comparator. See example.

  4. You can also sort Java ArrayList in descending order using Java Stream API's sorted() method and then collect it into a separate List. That way you can retain the original list. See example.

You must also know about the overloaded sort method 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

Java 8 onward there is also a Comparator.reverseOrder() method that can be used to sort an ArrayList in descending order in Java.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
    cityList.sort(Comparator.reverseOrder());
    System.out.println(cityList);

  }
}

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);
  }    
}

Sorting Java ArrayList Using Java Stream sorted()

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortListDemo {
  public static void main(String[] args) {
    
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
   
    List<String> sortedList = cityList.stream()
                                      .sorted(Comparator.reverseOrder())
                                      .collect(Collectors.toList());
    System.out.println(sortedList);
  }
}

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 HashMap Works Internally in Java
  2. Difference Between CountDownLatch And CyclicBarrier in Java
  3. Java Phaser With Examples
  4. Varargs (Variable-length Arguments) 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

No comments:

Post a Comment