I have a List of doubles in java and I want to sort ArrayList in descending order.
Input ArrayList is as below:
List<Double> testList = new ArrayList(); testList.add(0.5); testList.add(0.2); testList.add(0.9); testList.add(0.1); testList.add(0.1); testList.add(0.1); testList.add(0.54); testList.add(0.71); testList.add(0.71); testList.add(0.71); testList.add(0.92); testList.add(0.12); testList.add(0.65); testList.add(0.34); testList.add(0.62);
The out put should be like this
0.92 0.9 0.71 0.71 0.71 0.65 0.62 0.54 0.5 0.34 0.2 0.12 0.1 0.1 0.1
An ArrayList can be sorted in two ways ascending and descending order. The collection class provides two methods for sorting ArrayList. sort() and reverseOrder() for ascending and descending order respectively.
There are multiple ways to sort a list in Java 8, for example, you can get a stream from the List and then use the sorted() method of Stream class to sort a list like ArrayList, LinkedList, or Vector and then convert back it to List. Alternatively, you can use the Collections. sort() method to sort the list.
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections
though!
Here is the documentation for Collections
.
Descending:
Collections.sort(mArrayList, new Comparator<CustomData>() { @Override public int compare(CustomData lhs, CustomData rhs) { // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With