亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

狐的傳說 2021-04-05 10:20:23
我創建了一個要根據第二列排序的2D數組。我檢查了其他變體,但是它們似乎不起作用。目前,數據作為第一組出現,我想獲得第二組。0 0                 0 01 1065              6 242 70                3 603 60                2 704 90                4 905 251               5 2516 24                7 5587 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]));        }    });}}
查看完整描述

2 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

您可以使用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());

    }


    }


查看完整回答
反對 回復 2021-04-21
  • 2 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號