There are multiple way to sort and reverse a double list elements.
Using java 8 sorted() and Comparator.reverseOrder() method :-
- First convert Arrays to list using Arrays.asList method.
- Now, get Stream data from List using arrayList.stream() method.
- Here Stream sorted() method returns a stream of the elements according to natural order.
- Comparator.reverseOrder() method returns a comparator that reverse of natural order elements using Comparable objects.
- Now printing the descending sorted list elements.
Using java 7 sort() and Collections.reverseOrder() method :-
- Using sort() method of Collections class to sort the elements and passing list.
- Using Collections.reverseOrder() method to sort the elements in descending order.
- Now printing the descending sorted list elements.
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() method
List decimalList = Arrays.asList(11.45, 23.87, 17.54, 32.89, 98.78, 21.34, 56.54, 121.78);
// System.out.println("using java 8:- ");
List dList = decimalList.stream().sorted().sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("Using java 8 :- " + dList);
// Using java 7 sort() and Collections.reverseOrder() method
Collections.sort(decimalList, Collections.reverseOrder());
System.out.println("Using java 7 :- " + decimalList);
}
}
Output :-
Using java 8 :- [121.78, 98.78, 56.54, 32.89, 23.87, 21.34, 17.54, 11.45]
Using java 7 :- [121.78, 98.78, 56.54, 32.89, 23.87, 21.34, 17.54, 11.45]