如何使用自定义比较器对整数数组进行排序?

我需要使用自定义比较器对整数数组进行排序,但是Java的库没有为具有比较器的整数提供排序功能(比较器只能与对象一起使用)。有没有简单的方法可以做到这一点?



长风秋雁
浏览 741回答 3
3回答

慕姐8265434

如果您无法更改输入数组的类型,则可以执行以下操作:final int[] data = new int[] { 5, 4, 2, 1, 3 };final Integer[] sorted = ArrayUtils.toObject(data);Arrays.sort(sorted, new Comparator<Integer>() {&nbsp; &nbsp; public int compare(Integer o1, Integer o2) {&nbsp; &nbsp; &nbsp; &nbsp; // Intentional: Reverse order for this demo&nbsp; &nbsp; &nbsp; &nbsp; return o2.compareTo(o1);&nbsp; &nbsp; }});System.arraycopy(ArrayUtils.toPrimitive(sorted), 0, data, 0, sorted.length);这可以使用ArrayUtilscommons-lang项目轻松地在int[]和之间进行转换Integer[],创建数组的副本,进行排序,然后将排序后的数据复制到原始副本上。

跃然一笑

使用流(Java 8)怎么样?int[] ia = {99, 11, 7, 21, 4, 2};ia = Arrays.stream(ia).&nbsp; &nbsp; boxed().&nbsp; &nbsp; sorted((a, b) -> b.compareTo(a)). // sort descending&nbsp; &nbsp; mapToInt(i -> i).&nbsp; &nbsp; toArray();或就地:int[] ia = {99, 11, 7, 21, 4, 2};System.arraycopy(&nbsp; &nbsp; &nbsp; &nbsp; Arrays.stream(ia).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; boxed().&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sorted((a, b) -> b.compareTo(a)). // sort descending&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapToInt(i -> i).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; toArray(),&nbsp; &nbsp; &nbsp; &nbsp; 0,&nbsp; &nbsp; &nbsp; &nbsp; ia,&nbsp; &nbsp; &nbsp; &nbsp; 0,&nbsp; &nbsp; &nbsp; &nbsp; ia.length&nbsp; &nbsp; );

弑天下

如果您不想复制数组(例如,数组很大),则可能需要创建一个List<Integer>可用于排序的包装器:final int[] elements = {1, 2, 3, 4};List<Integer> wrapper = new AbstractList<Integer>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public Integer get(int index) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return elements[index];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public int size() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return elements.length;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public Integer set(int index, Integer element) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int v = elements[index];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elements[index] = element;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return v;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };现在,您可以使用自定义比较器对此包装器列表进行排序。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java