在Java中将数组按降序排序

huangapple 未分类评论55阅读模式
标题翻译

Sorting array in descending order in java

问题

我试图对名为"efficiency"的数组进行降序排序,就像这样:

Arrays.sort(efficiency, (a, b) -> b - a)

然而,它抛出了一个异常,表示没有找到合适的方法。
然后我查阅了文档,发现实际上存在着这个方法:

sort​(T[] a, Comparator<? super T> c)

这是什么问题呢?

英文翻译

I was trying to sort an array called efficiency in descending order just like this:

Arrays.sort(efficiency, (a, b) -> b - a)

However, it throws an exception that no suitable method has been found.
I then check the Documentation and found that there actually is the method

	sort​(T[] a, Comparator<? super T> c)

What's wrong with that?

答案1

得分: 0

假设数组具有非基本数据类型,您可以使用以下代码:

Arrays.sort(efficiency, Collections.reverseOrder());

对于特定于lambda的方法,您可以查看这个详细的回答:

https://stackoverflow.com/a/21970805/10171575

英文翻译

Assuming the array has a non-primitive datatype, you could use the following:

Arrays.sort(efficiency, Collections.reverseOrder());

For a lambda specific approach I would check out this detailed answer:

https://stackoverflow.com/a/21970805/10171575

huangapple
  • 本文由 发表于 2020年3月16日 13:46:20
  • 转载请务必保留本文链接:https://java.coder-hub.com/60700891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定