How to sort an ArrayList?
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;
}
});
For your example, this will do the magic in Java 8
List<Double> testList = new ArrayList();
testList.sort(Comparator.naturalOrder());
But if you want to sort by some of the fields of the object you are sorting, you can do it easily by:
testList.sort(Comparator.comparing(ClassName::getFieldName));
or
testList.sort(Comparator.comparing(ClassName::getFieldName).reversed());
or
testList.stream().sorted(Comparator.comparing(ClassName::getFieldName).reversed()).collect(Collectors.toList());
Sources: https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
Use util method of java.util.Collections class, i.e
Collections.sort(list)
In fact, if you want to sort custom object you can use
Collections.sort(List<T> list, Comparator<? super T> c)
see collections api