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
Just use loop or default sort() function.
With Java8 there is a default sort method on the List interface that will allow you to sort the collection if you provide a Comparator. You can easily sort the example in the question as follows:
Note: the args in the lambda are swapped when passed in to Double.compare to ensure the sort is descending
|*| Sorting an List :
|=> Sort Asc Order :
|=> Sort Dsc Order :
|*| Reverse the order of List :
Use util method of java.util.Collections class, i.e
In fact, if you want to sort custom object you can use
see collections api
You can use
Collections.sort(list)
to sortlist
if yourlist
containsComparable
elements. Otherwise I would recommend you to implement that interface like here:and of course provide your own realization of
compareTo
method like here:And then you can again use
Colection.sort(list)
as now list contains objects of Comparable type and can be sorted. Order depends oncompareTo
method. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html for more detailed information.