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);
Share:
87,569
Eldar Nezametdinov
Author by

Eldar Nezametdinov

Updated on July 09, 2022

Comments

  • Eldar Nezametdinov
    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
    JHS over 10 years
    Does this sort in the descending order or just reverse the order in which the elements were inserted?
  • Eldar Nezametdinov
    Eldar Nezametdinov over 10 years
    It just reverse the order elements.
  • Loa
    Loa about 7 years
    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.
  • Pshemo
    Pshemo over 6 years
    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())
  • parsecer
    parsecer almost 4 years
    This 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
    Akhil about 3 years
    The question in misleading, if the intent was to just reverse the list, this will work.
  • Masuri
    Masuri over 2 years
    It should've been selected as an answer. this is exactly what I've been looking for.
  • T77
    T77 almost 2 years
    Or just list.sort(Collections.reverseOrder());