鍍金池/ 問答/Java/ 怎么進行java數(shù)組逆序排序?

怎么進行java數(shù)組逆序排序?

nums 數(shù)組里是int型。
Arrays.sort(nums)默認為升序排序,要進行降序排序需要自己寫個Comparator,但是為什么不能這樣寫呢?

   class MyComparator implements Comparator<Integer> {
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        }
        Comparator cmp = new MyComparator();

        Arrays.sort(nums, cmp);

報錯顯示不能用Integer,想問java里有沒有庫能直接逆序排序的?

回答
編輯回答
喜歡你

0-i就好了

2017年3月29日 12:18
編輯回答
不歸路

guava值得我們學習。Arrays.sort(nums, Ordering.natural().reverse());

2018年5月25日 03:39
編輯回答
吢丕

Java 里沒有Comparator<int>,而且int[]也不能直接轉(zhuǎn)Integer[]。

建議手動轉(zhuǎn)成Integer[]或者List<Integer>再操作。

2018年8月25日 16:22
編輯回答
愛是癌

nums 具體是什么類型?報的什么錯?如果 nums 的順序已經(jīng)確定您只是想反轉(zhuǎn),你可以簡單些幾行代碼把首尾調(diào)一下,或者用 apache-commons 的 ArrayUtils.reverse

報錯貼出來看看。

2018年2月8日 13:50
編輯回答
雅痞

nums 具體是什么類型?報的什么錯?如果 nums 的順序已經(jīng)確定您只是想反轉(zhuǎn),你可以簡單些幾行代碼把首尾調(diào)一下,或者用 apache-commons 的 ArrayUtils.reverse

2017年4月21日 16:26
編輯回答
笨小蛋

如果你用上了 Java8,可能流式操作看起來會稍微好一點:

int[] nums = {1, 2, 0, 3, 5, 4};

nums = IntStream.of(nums)  // 變?yōu)?IntStream
        .boxed()           // 變?yōu)?Stream<Integer>
        .sorted(Comparator.reverseOrder()) // 按自然序的相反序排序
        .mapToInt(Integer::intValue)       // 變?yōu)?IntStream
        .toArray();  // 變?yōu)?int[]

System.out.println(Arrays.toString(nums));

沒用上 Java8 的話...

  1. 要么自己寫/找排序算法;
  2. 要么先將 int[] 轉(zhuǎn)為 Integer[],排序完之后又將 Integer[] 轉(zhuǎn)化為 int[](捂臉)
  3. 要么先排序,再寫個簡單的方法反轉(zhuǎn)數(shù)組...
2018年1月10日 05:44
編輯回答
熟稔

有的。nums.sort((p1, p2) -> p1.compareTo(p2));

2017年6月19日 12:36
編輯回答
深記你

簡單的,你可以在升序排序后自己把數(shù)據(jù)翻轉(zhuǎn)一下不就完了么.

2018年8月22日 19:13
編輯回答
莫小染

附上代碼:

        class MyComparator implements Comparator<Integer> {
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        }
        
        Comparator cmp = new MyComparator();
        List<Integer> numList = new ArrayList<>();
        numList.add(1);
        numList.add(2);
        Integer[] nums = numList.toArray(new Integer[numList.size()]);
        Arrays.sort(nums,cmp);
        for (Integer n : nums){
            System.out.println(n);
        }
2017年12月3日 05:08
編輯回答
短嘆
public static void main(String[] args) {
        List<Integer> nums = Lists.newArrayList(2,5,9,3,4);
        Collections.sort(nums, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        for(Integer num : nums){
            System.out.println(num);
        }
    }

這樣就是從小到大排序了,如果要從大到小排序,那就加個負號就行

return -o1.compareTo(o2);
2018年7月8日 11:32