簡體   English   中英

基於第二列的2d int數組排序

[英]2d int Array sorting based on second column

我創建了一個要根據第二列排序的2D數組。 我檢查了其他變體,但是它們似乎不起作用。

目前,數據作為第一組出現,我想獲得第二組。

0 0                 0 0
1 1065              6 24
2 70                3 60
3 60                2 70
4 90                4 90
5 251               5 251
6 24                7 558
7 558               1 1065 

目前,我的代碼是:

import java.util.Arrays;
import java.util.Comparator;

public class Testing {

public static void test() {
    int[][] arrayToSort = {{0, 1,2,3,4,5,6,7}, {0, 1065, 70, 60,90,251,24,558}};

}

public static void sortArray(int myArray[][]) {
    Arrays.sort(myArray, new Comparator<int[]>() {

        @Override
        public int compare(int[] o1, int[] o2) {
            return Integer.valueOf(o1[1]).compareTo(Integer.valueOf(o2[1]));
        }

    });
}

}

您可以使用TreeMap將數組的第二行存儲為鍵,將第一行存儲為值。

由於key的值是整數,因此您無需創建任何新的Comparator / Comparable類即可對其進行排序。 TreeMap將自動按升序存儲它們。

public static void main(String[] args)  {
int[][] ax = {{0, 1,2,3,4,5,6,7}, 
              {0, 1065, 70, 60,90,251,24,558} };

        Map<Integer,Integer> map = new TreeMap<>();

        for (int i = 0; i < ax[0].length; i++) {
            map.put(ax[1][i], ax[0][i] );
        }

    // Iterate over the TreeMap to get as per your wish order

       for (Map.Entry<Integer, String> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() 
                                  + " Value : " + entry.getValue());
    }

    }

您的方法是對外部數組進行排序-僅包含兩個元素(即數組)。 將您的問題想象成具有兩個單獨的數組: {0,1,2,3,4,5,6,7}{0,1065,70,60,90,251,24,558} 然后,您的問題是對第二個數組進行排序,並在第一個數組中進行相同的交換。 我要說的是,您的數據結構通常不適用於此任務。 考慮使用成對清單:

public class Testing {

    private static class MyNumber {
        private final int id;
        private final int number;

        public MyNumber(int id, int number) {
            this.id = id;
            this.number = number;
        }

        public int getId() {
            return id;
        }

        public int getNumber() {
            return number;
        }
    }

    public static void main(String[] args) {
        int[][] arrayToSort = {
                {0, 1,    2,  3,  4,  5,   6,  7  },
                {0, 1065, 70, 60, 90, 251, 24, 558}
        };

        List<MyNumber> list = IntStream.range(0, arrayToSort[0].length)
                .mapToObj(i -> new MyNumber(arrayToSort[0][i], arrayToSort[1][i]))
                .collect(toList());

        Collections.sort(list, Comparator.comparing(MyNumber::getNumber));

        for (MyNumber myNumber : list) {
            System.out.println(myNumber.getId() + " " + myNumber.getNumber());
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM