Sorting an ArrayList
in descending order in Java can be done using various approaches. The most common and straightforward way is by using the Collections.sort
method along with a custom comparator or by using the sort
method with a lambda expression. Here's how you can do it:
How to Sort an ArrayList in Descending Order:
- Using
Collections.sort
with a Custom Comparator:
The Collections.sort
method can be used with a custom comparator to sort the list in descending order.
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class SortArrayListDescending {
public static void main(String args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(5);
list.add(30);
// Using Collections.sort with a custom Comparator
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
System.out.println("Sorted list in descending order: " + list);
}
}
- Using
Collections.sort
with a Lambda Expression:
A more concise way to achieve the same result is by using a lambda expression.
import java.util.ArrayList; import java.util.Collections; public class SortArrayListDescending {
public static void main(String args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(5);
list.add(30);
// Using Collections.sort with a lambda expression
Collections.sort(list, (a, b) -> b - a);
System.out.println("Sorted list in descending order: " + list);
}
}
- Using the
sort
Method with a Lambda Expression:
Java 8 introduced the sort
method for the List
interface, which can also be used with a lambda expression.
import java.util.ArrayList; public class SortArrayListDescending {
public static void main(String args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(5);
list.add(30);
// Using the List's sort method with a lambda expression
list.sort((a, b) -> b - a);
System.out.println("Sorted list in descending order: " + list);
}
}