Sobes.tech
Junior — Middle

How can data be sorted in descending order?

sobes.tech AI

Answer from AI

In Java, to sort data in descending order, you can use the sort method from the Collections or Arrays class with a comparator that defines the reverse order.

Example of sorting a list of numbers in descending order:

import java.util.*;

public class SortDescending {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 9);
        // Sorting in descending order
        numbers.sort(Comparator.reverseOrder());
        System.out.println(numbers); // Outputs [9, 8, 5, 3, 1]
    }
}

For arrays, you can use:

Integer[] arr = {5, 3, 8, 1, 9};
Arrays.sort(arr, Comparator.reverseOrder());

If you are sorting objects by some field, you need to implement a corresponding comparator with the reverse order.

How can data be sorted in descending order? — Java - sobes.tech