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.
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.
Use this:
Collections.reverse(list);
There is a method reverseOrder
in the Collections
class which returns a Comparator
.
You can use it like Collections.sort(list, Collections.reverseOrder());
How I would do it is:
personsList.sort(Comparator.comparing(Person::getAge, Comparator.reverseOrder()));
And happy coding :)
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());
}
});
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);
To reverse the order of items in List you can use Collections.reverse(List<?> list)
Collections.reverse(List)
reverses the given list in place. You can also use Guava's Lists.reverse(List)
to create a view backed by the given list that is in reverse order without copying it or modifying the original list.
And if you just want to create a list that is sorted in the reverse of the natural order, see @assylias's answer about Ordering.natural().reverse()
.
Try this neater approach:
Collections.reverseOrder(
Comparator.comparing(
MyEntity::getAFieldToSortBy)));