How to Sort a List of Doubles in Descending Order in Java

Learn how to sort a list of Doubles in descending order in Java using Java 8 Stream sorted(), Comparator.reverseOrder() and Collections.sort().

Code Explanation (Step-by-Step) :-

Using Java 8 sorted() and Comparator.reverseOrder()

  • First, create a list of Double elements using the Arrays.asList() method.
  • Next, create a stream from the list using the stream() method.
  • Use sorted(Comparator.reverseOrder()) to sort the stream elements in descending order.
  • Comparator.reverseOrder() returns a comparator that imposes the reverse of the natural ordering on the elements.
  • Now, collect the sorted elements into a list using Collectors.toList() and print the result.

Using Collections.sort() and Collections.reverseOrder()

  • Use the Collections.sort() method to sort the elements of the list.
  • Pass Collections.reverseOrder() as the comparator to sort the elements in descending order.
  • Now, print the list containing the elements sorted in descending order.

              Syntax : Collections.sort(decimalList, Collections.reverseOrder());

				
					import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {

        // Using Java 8 sorted() and Comparator.reverseOrder()
        List<Double> decimalList = Arrays.asList(
                11.45, 23.87, 17.54, 32.89,
                98.78, 21.34, 56.54, 121.78
        );

        List<Double> dList = decimalList.stream()
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());

        System.out.println("Using Java 8: " + dList);

        // Using Collections.sort() and Collections.reverseOrder()
        Collections.sort(decimalList, Collections.reverseOrder());

        System.out.println("Using Collections.sort(): " + decimalList);
    }
}
				
			

Output :-
Using Java 8: [121.78, 98.78, 56.54, 32.89, 23.87, 21.34, 17.54, 11.45]
Using Collections.sort(): [121.78, 98.78, 56.54, 32.89, 23.87, 21.34, 17.54, 11.45]

Sort Double Values in Ascending Order

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {

        List<Double> decimalList = Arrays.asList(
                11.45, 23.87, 17.54, 32.89,
                98.78, 21.34, 56.54, 121.78
        );

        List<Double> sortedList = decimalList.stream()
                .sorted()
                .collect(Collectors.toList());

        System.out.println(sortedList);
    }
}
				
			

Output :-
[11.45, 17.54, 21.34, 23.87, 32.89, 56.54, 98.78, 121.78]