Sort List in reverse in order
87,569
Solution 1
Use this:
Collections.reverse(list);
Solution 2
There is a method reverseOrder
in the Collections
class which returns a Comparator
.
You can use it like Collections.sort(list, Collections.reverseOrder());
Solution 3
How I would do it is:
personsList.sort(Comparator.comparing(Person::getAge, Comparator.reverseOrder()));
And happy coding :)
Solution 4
you can reverse any type by just putting "-" or negative sign infront of your return.
Collections.sort(listed, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return -o1.getLeft().compareTo(o2.getLeft());
}
});
Solution 5
If you want to sort the list in reverse natural order, guava's Ordering has a reverse method:
List<String> list = Ordering.natural().reverse().sortedCopy(asu2);
Author by
Eldar Nezametdinov
Updated on July 09, 2022Comments
-
Eldar Nezametdinov almost 2 years
I have List list1 in direct order.
List<String> list = Ordering.natural().sortedCopy(asu2);
How to change order. And I don't know how to rewrite methods from extends class, please write with examples or speak clearly.
-
JHS over 10 yearsDoes this sort in the descending order or just reverse the order in which the elements were inserted?
-
Eldar Nezametdinov over 10 yearsIt just reverse the order elements.
-
Loa about 7 yearsI would consider your answer, since it would not be necessary to arrange for only after reverting. Your approach is capable of performing two operations in a single frame. I don't know about the others, but thank you.
-
Pshemo over 6 yearsAnd lets hope that
compareTo
will never return minimal integer because-Integer.MIN_VALUE
is stillInteger.MIN_VALUE
. Safest way would be swapping o1 with o2 likereturn o2.getLeft().compareTo(o1.getLeft())
-
parsecer almost 4 yearsThis answer is misleading. It doesn't sort a collection in descending order - merely switches last element with first, second to last with second, etc
-
Akhil about 3 yearsThe question in misleading, if the intent was to just reverse the list, this will work.
-
Masuri over 2 yearsIt should've been selected as an answer. this is exactly what I've been looking for.
-
T77 almost 2 yearsOr just
list.sort(Collections.reverseOrder());