将数组按照另一个数组数据对应排序 Java

使用多维数组调用Arrays.sort(arr,Comparator);

如:这里将profits按照captital排列后的顺序进行排列

int[] profits = new int[]{3, 2, 1};
int[] capital = new int[]{2, 0, 1};
//获取profits大小
int n = profits.length;
//新建对应的二维数组
int[][] sorted = new int[n][2];
//注入数组信息
for (int i = 0; i < n; i++) {
    sorted[i][0] = capital[i];
    sorted[i][1] = profits[i];
}
//在Arrays.sort()重载方法中,new Comparator对象
Arrays.sort(sorted, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return o1[0]-o2[0];
    }
});
//写会队列
for (int i = 0; i < n; i++) {
    capital[i] = sorted[i][0];
    profits[i] = sorted[i][1];
}
for (int i = 0; i < n; i++) {
    System.out.print(profits[i]);
}
System.out.println();
for (int i = 0; i < n; i++) {
    System.out.print(capital[i]);
}

输出:

213

012

重排后为

profits={2,1,3};

capital={0,1,2};

    原文作者:天道饶
    原文地址: https://blog.csdn.net/efduke/article/details/123499325
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞