使用 java 8 功能(流、lambda 等)按降序对 int 数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31778114/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:36:36  来源:igfitidea点击:

Sort int array in descending order using java 8 features (stream, lambda, etc)

javajava-8

提问by JBT

Surprisingly, it seems there was no simple, one-liner kind of solution in java to sort int array in descending order before java 8. For example, check this post. Now that we have java 8, is there an elegant, simple, one-liner way using java 8 features, such as stream and lambda expression, to sort an int array in descending order?

令人惊讶的是,在 java 8 之前,java 中似乎没有简单的、单行的解决方案来按降序对 int 数组进行排序。例如,查看这篇文章。现在我们有了 java 8,是否有一种优雅、简单、单行的方式使用 java 8 的特性(例如流和 lambda 表达式)按降序对 int 数组进行排序?

Edit
I am interested in a solution for int[], not Integer[].

编辑
我对 的解决方案感兴趣int[],而不是Integer[]

Edit
I am interested in a solution that only uses JAVA SE library.

编辑
我对仅使用 JAVA SE 库的解决方案感兴趣。

采纳答案by Pshemo

With guava you could simply write

用番石榴你可以简单地写

Ints.asList(a).sort(Comparator.reverseOrder());

It may be not so efficient since it requires boxing int to Integer, but it is elegant one-liner.

它可能不是那么有效,因为它需要将 int 装箱到 Integer,但它是优雅的单行。

You can also write something like

你也可以写类似的东西

int[] sorted = IntStream.of(a)
        .boxed()
        .sorted(Comparator.reverseOrder())
        .mapToInt(i -> i)
        .toArray();

but this also suffers from boxing and it needs to create new array.

但这也受到拳击的影响,它需要创建新数组。

Anyway I doubt you will find nice solution in standard Java free of boxing since Comparator<T>can accept only objects. For now best way would be using Arrays.sortand reverse its order manually.

无论如何,我怀疑您是否会在没有装箱的标准 Java 中找到很好的解决方案,因为它Comparator<T>只能接受对象。目前最好的方法是Arrays.sort手动使用和反转其顺序。

回答by Alexis C.

int[] arr = ...;
Arrays.sort(arr);
int[] reversed = IntStream.range(0, arr.length)
                          .map(i -> arr[arr.length-i-1])
                          .toArray();

is probably the closest you could do if you don't want to box the intinto its respective wrapper class for each value in the array.

如果您不想int将数组中的每个值装箱到其各自的包装类中,这可能是您能做的最接近的事情。

If you suffer from performances by doing the sort once (O(nlogn)) and the reverse operation after (O(n)), you might want to look into Arrays.parallelSortand parallelize the IntStream.

如果您因执行一次排序 ( O(nlogn)) 和 ( O(n))之后的反向操作而受到性能影响,您可能需要查看Arrays.parallelSort并并行化IntStream.