gpt4 book ai didi

java - 如何仅在java中使用lambda按升序和降序对整数数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:10 32 4
gpt4 key购买 nike

int[] arr2 = new int[] {54, 432, 53, 21, 43};

我正在使用它进行排序,但出现错误。

Arrays.sort(arr2, (a, b) -> a - b);

这也会报错。

arr2.sort((a, b) -> a - b);

最佳答案

您可以将 Integer[] 类型的输入排序为:

Integer[] arr2 = new Integer[] {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());

或者可能使用原始类型作为:

int[] arr2 = new int[]{54, 432, 53, 21, 43};
int[] sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();

或进一步使用现有答案之一的技巧(请注意,它应该谨慎地与边界值一起使用):

int[] sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();

编辑:对于就地升序排序,您只需执行:

int[] arr2 = new int[]{54, 432, 53, 21, 43};
Arrays.sort(arr2);

关于java - 如何仅在java中使用lambda按升序和降序对整数数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126952/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com