54

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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Eldar Nezametdinov
  • 1,917
  • 4
  • 21
  • 23

9 Answers9

121

Use this:

Collections.reverse(list);
morgano
  • 17,210
  • 10
  • 45
  • 56
59

There is a method reverseOrder in the Collections class which returns a Comparator.

You can use it like Collections.sort(list, Collections.reverseOrder());

JHS
  • 7,761
  • 2
  • 29
  • 53
  • I 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. – Loa Mar 26 '17 at 20:20
  • 2
    Or just `list.sort(Collections.reverseOrder());` – T77 Jul 07 '22 at 00:32
41

How I would do it is:

personsList.sort(Comparator.comparing(Person::getAge, Comparator.reverseOrder()));

And happy coding :)

18

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());

    }
});
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
  • 4
    And lets hope that `compareTo` will never return minimal integer because `-Integer.MIN_VALUE` is still `Integer.MIN_VALUE`. Safest way would be swapping o1 with o2 like `return o2.getLeft().compareTo(o1.getLeft())` – Pshemo Sep 29 '17 at 21:31
8

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);
assylias
  • 321,522
  • 82
  • 660
  • 783
3

To reverse the order of items in List you can use Collections.reverse(List<?> list)

Aritz
  • 30,971
  • 16
  • 136
  • 217
1

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().

ColinD
  • 108,630
  • 30
  • 201
  • 202
1

Try this neater approach:

Collections.reverseOrder(
  Comparator.comparing(
    MyEntity::getAFieldToSortBy)));
Zon
  • 18,610
  • 7
  • 91
  • 99
0

list.sort(Comparator.reverseOrder());

Alex G
  • 718
  • 1
  • 7
  • 9