Java数组降序排序?
有没有简单的方法可以按降序对数组进行排序,就像在 数组类?
或者我必须停止偷懒并自己做这件事:[
Is there any EASY way to sort an array in descending order like how they have a sort in ascending order in the Arrays class?
Or do I have to stop being lazy and do this myself :[
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
您可以使用它对所有类型的对象进行排序
Arrays.sort()
不能直接用于按降序对原始数组进行排序。如果您尝试通过传递Collections.reverseOrder()
定义的反向比较器来调用Arrays.sort()
方法,它将抛出错误这对于“对象数组”(例如整数数组)可以正常工作,但不适用于原始数组(例如 int 数组)。
按降序对原始数组进行排序的唯一方法是,首先按升序对数组进行排序,然后就地反转数组。对于二维基本数组也是如此。
You could use this to sort all kind of Objects
Arrays.sort()
cannot be used directly to sort primitive arrays in descending order. If you try to call theArrays.sort()
method by passing reverse Comparator defined byCollections.reverseOrder()
, it will throw the errorThat will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.
The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.
对于列表
对于数组
for a list
for an array
您可以使用以下方法:
Collections.reverseOrder()
使用逆自然顺序返回一个Comparator
。您可以使用Collections.reverseOrder(myComparator)
获得您自己的比较器的反转版本。You can use this:
Collections.reverseOrder()
returns aComparator
using the inverse natural order. You can get an inverted version of your own comparator usingCollections.reverseOrder(myComparator)
.另一种方法是(对于数字!!!)
字面意思:
an alternative could be (for numbers!!!)
Literally spoken:
没有显式比较器:
有显式比较器:
without explicit comparator:
with explicit comparator:
使用
Arrays.sort()
和 < 无法直接对基元数组(即int[] arr = {1, 2, 3};
)进行反向排序code>Collections.reverseOrder() 因为这些方法需要引用类型 (Integer
) 而不是基本类型 (int
)。但是,我们可以使用 Java 8 Stream 首先对数组进行装箱,然后按相反的顺序进行排序:
It's not directly possible to reverse sort an array of primitives (i.e.,
int[] arr = {1, 2, 3};
) usingArrays.sort()
andCollections.reverseOrder()
because those methods require reference types (Integer
) instead of primitive types (int
).However, we can use Java 8 Stream to first box the array to sort in reverse order:
首先,您需要使用以下方法对数组进行排序:
然后您需要使用以下方法将顺序从升序反转为降序:
First you need to sort your array using:
Then you need to reverse the order from ascending to descending using:
Java 8:
更新:
reversed()
反转指定的比较器。通常,比较器按升序排列,因此这会将顺序更改为降序。Java 8:
Update:
reversed()
reverses the specified comparator. Usually, comparators order ascending, so this changes the order to descending.对于包含原语元素的数组,如果有 org.apache.commons.lang(3) 可供使用,则反转数组(排序后)的简单方法是使用:
For array which contains elements of primitives if there is
org.apache.commons.lang(3)
at disposal easy way to reverse array (after sorting it) is to use:当数组是 Integer 类类型时,可以使用以下方法:
当数组是 int 数据类型时,可以使用以下方法:
When an array is a type of Integer class then you can use below:
When an array is a type of int data type then you can use below:
我不知道您的用例是什么,但是除了这里的其他答案之外,另一个(惰性)选项是仍然按照您指示的升序排序,但然后按相反顺序进行迭代。
I don't know what your use case was, however in addition to other answers here another (lazy) option is to still sort in ascending order as you indicate but then iterate in reverse order instead.
对于上面的讨论,这里有一个简单的示例,用于按降序对原始数组进行排序。
输出:
For discussions above, here is an easy example to sort the primitive arrays in descending order.
Output:
对于按降序排序的 2D 数组,您只需翻转参数输出的位置即可
降序排列
For 2D arrays to sort in descending order you can just flip the positions of the parameters
Output for descending
另一个解决方案是,如果您使用Comparable接口,您可以切换在compareTo(Object bCompared)中指定的输出值。
例如:
其中 magnitude 是我的程序中数据类型为 double 的属性。这是按照我定义的类 freq 的大小以相反的顺序对其进行排序。因此,为了纠正这个问题,您可以切换
<
和>
返回的值。这将为您提供以下结果:要使用此compareTo,我们只需调用
Arrays.sort(mFreq)
,它将为您提供排序后的数组freq [] mFreq
。该解决方案的优点(在我看来)在于它可以用于对用户定义的类进行排序,甚至比按特定属性对它们进行排序更重要。如果 Comparable 接口的实现听起来令人畏惧,我鼓励您不要这样想,实际上并非如此。这个关于如何实现可比较的链接使事情变得更加重要对我来说更容易。希望人们能够使用这个解决方案,并且您的喜悦甚至可以与我的相媲美。
Another solution is that if you're making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared).
For Example :
Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it's magnitude. So in order to correct that, you switch the values returned by the
<
and>
. This gives you the following :To make use of this compareTo, we simply call
Arrays.sort(mFreq)
which will give you the sorted arrayfreq [] mFreq
.The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I'd encourage you not to think that way, it actually isn't. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine.
在这里添加我针对几种不同场景的答案
对于数组
FWIW 列出
所有集合
Adding my answer in here for a couple of different scenarios
For an Array
FWIW Lists
Any and all Collections
但 Arrays.sort() 不适用于 int[] 等原始对象。对他们来说,它会抛出,
Arrays.sort() 只能按升序处理原始对象。
最好转成集合然后排序
But Arrays.sort() will not work with primitive objects like int[]. For them it will throw,
Arrays.sort() will work with primitive objects only in increasing order.
Better to convert into a collection and then sort
您可以使用 stream 操作( Collections.stream()) 与 Comparator.reverseOrder() 。
例如,假设您有这个集合:
要按“自然”顺序打印项目,您可以使用 sorted() 方法(或将其省略并得到相同的结果):
或者以降序(反向)顺序打印它们,您可以使用 sorted 方法,它采用 Comparator 并反转顺序:
请注意,这要求集合已实现 Comparable(如 Integer、String 等)。
You could use stream operations (Collections.stream()) with Comparator.reverseOrder().
For example, say you have this collection:
To print the items in their "natural" order you could use the sorted() method (or leave it out and get the same result):
Or to print them in descending (reverse) order, you could use the sorted method that takes a Comparator and reverse the order:
Note this requires the collection to have implemented Comparable (as do Integer, String, etc.).
这里发生了很多混乱 - 人们建议非原始值的解决方案,尝试从头开始实现一些排序算法,提供涉及额外库的解决方案,展示一些 hacky 等。原始问题的答案是 50 /50。对于那些只想复制/粘贴的人:
arrOfObjects
现在是{6,5,4,3,2,1}
。如果您有一个除整数以外的数组 - 使用相应的 object< /a> 而不是整数
。There is a lot of mess going on here - people suggest solutions for non-primitive values, try to implement some sorting algos from the ground, give solutions involving additional libraries, showing off some hacky ones etc. The answer to the original question is 50/50. For those who just want to copy/paste:
arrOfObjects
is{6,5,4,3,2,1}
now. If you have an array of something other than ints - use the corresponding object instead ofInteger
.对 int 数组进行降序排序的简单方法:
Simple method to sort an int array descending:
注意:这是 N log N 时间复杂度,但更容易阅读
并了解如何执行反向排序。
此解决方案的建议归功于 Ken。
NOTE: this is a N log N time complexity but easier to read through
and understand how to perform sort in reverse.
credits to Ken for suggestion of this solution.
我知道这是一个相当古老的线程,但这里是整数和 Java 8 的更新版本:
请注意,对于正常升序(或 Comparator.comparingInt()),它是“o1 - o2”。
这也适用于任何其他类型的对象。说:
I know that this is a quite old thread, but here is an updated version for Integers and Java 8:
Note that it is "o1 - o2" for the normal ascending order (or Comparator.comparingInt()).
This also works for any other kinds of Objects. Say:
这对我有用:
输出:
This worked for me:
Output:
只需使用此方法按降序对 double 类型的数组进行排序,您可以使用它对任何其他类型的数组(如 int、float 等)进行排序,只需更改“返回类型”、“参数类型”和将变量“x”类型转换为相应的类型。您还可以将 if 条件中的“>=”更改为“<=”以使顺序升序。
just use this method to sort an array of type double in descending order, you can use it to sort arrays of any other types(like int, float, and etc) just by changing the "return type", the "argument type" and the variable "x" type to the corresponding type. you can also change ">=" to "<=" in the if condition to make the order ascending.
使用比较器的另一种方法
Another way with Comparator
有时我们练习一个例子是件好事,这里有一个完整的例子:
sortdesc.java
编译它...
调用它...
< strong>输出
如果你想尝试一个字母数字数组...
你会得到如下输出:
来源
It's good sometimes we practice over an example, here is a full one:
sortdesc.java
compiling it...
calling it...
OUTPUT
If you want to try an alphanumeric array...
you gonna get the OUTPUT as follow:
source
有一种方法可能会有点长,但效果很好。这是一种对 int 数组进行降序排序的方法。
希望这能帮助某人,,,有一天:
There is a way that might be a little bit longer, but it works fine. This is a method to sort an int array descendingly.
Hope that this will help someone ,,, some day:
我有以下工作解决方案
I had the below working solution
这是我对原始类型 int 数组进行排序的方法。
结果:
Here is how I sorted a primitive type int array.
Result:
这适用于整数的基本类型示例。
首先是将数组按降序排序,然后循环遍历内容,但从排序数组的最后一个索引开始索引。
This is applicable for primitive types examples for integers.
First is to sort the array into descending order then loop through the contents but start the index into the last index of the sorted array.
不幸的是,在描述中排序非常复杂。命令。
最好只重载像 Arrays.sort(arr,verseOrder()) 这样的方法,
现在我看到以下选项:
Unfortunatley it's quite complicated to sort in desc. order.
It would be good to have just overloaded method like
Arrays.sort(arr, reverseOrder())
For now I see the following option: