Java 按相反顺序对列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18073590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort List in reverse in order
提问by Eldar Nezametdinov
I have List list1 in direct order. List<String> list = Ordering.natural().sortedCopy(asu2);
我有按直接顺序列出的 list1。 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.
如何更改顺序。而且我不知道如何重写 extends 类的方法,请举例说明或说清楚。
采纳答案by morgano
Use this:
用这个:
Collections.reverse(list);
回答by JHS
There is a method reverseOrderin the Collectionsclass which returns a Comparator.
有一种方法reverseOrder在Collections它返回一个类Comparator。
You can use it like Collections.sort(list, Collections.reverseOrder());
你可以像这样使用它 Collections.sort(list, Collections.reverseOrder());
回答by Damian Leszczyński - Vash
To reverse the order of items in List you can use Collections.reverse(List<?> list)
要反转 List 中项目的顺序,您可以使用 Collections.reverse(List<?> list)
回答by assylias
If you want to sort the list in reverse natural order, guava's Ordering has a reverse method:
如果要按自然顺序对列表进行排序,guava 的 Ordering 有一个反向方法:
List<String> list = Ordering.natural().reverse().sortedCopy(asu2);
回答by ColinD
Collections.reverse(List)reverses the given list in place. You can also use Guava's Lists.reverse(List)to create a viewbacked by the given list that is in reverse order without copying it or modifying the original list.
Collections.reverse(List)将给定的列表原地反转。您还可以使用 Guava'sLists.reverse(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().
如果您只想创建一个按自然顺序相反的顺序排序的列表,请参阅 @assylias 的关于Ordering.natural().reverse().
回答by Fikreselam Elala
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());
}
});
回答by panayot_kulchev_bg
How I would do it is:
我会怎么做是:
personsList.sort(Comparator.comparing(Person::getAge, Comparator.reverseOrder()));
And happy coding :)
和快乐编码:)

