English 中文(简体)
如何根据第二组分在两组阵列中打一栏?
原标题:How to sort the first column in a 2-dimensional array based on the second?

例如:

我阵列的第一栏是按数字顺序排列的。 第二栏是随机数字。 我想将第二栏按顺序排列,这当然会迫使第一栏偏离顺序。 任何想法如何在java这样做。 我已经找了,但似乎找不到适当的词汇。

最佳回答

您可以使用的方法是Arraysort(),其中你界定了自己的比较器,可以比较两维阵列的两行。

下面的代码分一个阵列,分两栏和十行,第一栏分类,第二栏完全随机。 然后按第二栏分类。

class Test{

    static void print(int[][] a){
        for (int i=0;i<a.length;i++){
            for (int j=0;j<a[0].length;j++) 
                System.out.print(a[i][j]+" ");
            System.out.println();
        }
    }

    public static void main(String[]args){

        java.util.Random r = new java.util.Random();
        int[][] a = new int[10][2];
        for (int i=0;i<a.length;i++){
            a[i][0]=i+1;
            a[i][1]=r.nextInt(100);
        }

        print(a);
        System.out.println();

        java.util.Arrays.sort(a, 
            new java.util.Comparator<int[]>(){
                public int compare(int[]a,int[]b){
                    return a[1]-b[1];
                }
        });

        print(a);
    }
}

例产出:

1 8 
2 49 
3 82 
4 89 
5 8 
6 0 
7 83 
8 89 
9 8 
10 46 

6 0 
1 8 
5 8 
9 8 
10 46 
2 49 
3 82 
7 83 
4 89 
8 89 
问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签