简体   繁体   English

如何在java中用整数值中的一列对多维字符串数组进行排序?

[英]How to sort multidimensional string array by one column in integer value in java?

I have for example this multidimensional array: 我有例如这个多维数组:

String[][] array = new String[10][2]; String [] [] array = new String [10] [2];

In the first column I have strings which are in my case usernames, but in the second column I have strings which should represent integers. 在第一列中,我有字符串,在我的情况下是用户名,但在第二列中,我有字符串,应该表示整数。 Now I want to sort the array like this: 现在我想像这样排序数组:

Before:

Petter 543
John   276
Jay    1879
Alf    5021
etc.

After:

Alf    5021
Jay    1879
Petter 543
John   276
etc.

So I want the highest value at the top and the lowest at the bottom but don't mess up the names. 所以我希望顶部的最高值和底部的最低值,但不要弄乱名字。 All I found till now is how to sort bother all integer multidimensional arrays or only string multidimensional arrays and not how to just sort the second column based on just integers. 到目前为止,我发现的是如何排序所有整数多维数组或只是字符串多维数组,而不是如何只基于整数排序第二列。

I once got it sorted but it was sorted in "alphabetic" way: 我曾经对它进行了排序,但它以“字母”方式排序:

So 1000 was the highest score 12 was the second highest score and 999999 was the lowest score. 所以1000分是最高分12分是第二高分,999999分是最低分。

Like 1 represents "a" and 9 represents "z". 1表示“a”,9表示“z”。

If the person and the id are associated in some way, then it would be better to create a class that models them ( POJO ), make that POJO class comparable , define a list of the POJO and use Collections#sort to sorted according to the desired criteria... 如果personid以某种方式关联,那么最好创建一个对它们进行建模的类( POJO ),使POJO可比 ,定义POJO列表并使用Collections #sort来排序。期望的标准......

another thing to consider is that you have a 2 dimentional String array String[][] but your question states 另一件需要考虑的事情是你有一个2维的字符串数组String [] [],但你的问题是

...How to sort multidimensional string array by one column in integer value in java? ...如何在java中整数值的一列对多维字符串数组进行排序

which means that you need to consider to parse the string to integer... (just as a nice hint) 这意味着你需要考虑将字符串解析为整数...(就像一个很好的提示)

public class MyPojo implement Comparator<MyPojo>{

private String name;

private String id;
...implements the method of the comparator 

}

the do in the main test class 在主测试类中做

List<MyPojo> mList = new ArrayList<MyPojo>();
mList.add(...);
mList.add(...);
mList.add(...);



Collections.sort(mList);
System.out.println(mList)

Using Java 8 streams: 使用Java 8流:

String[][] out = Arrays.stream(names)
    .sorted(Comparator.comparing(x -> -Integer.parseInt(x[1])))
    .toArray(String[][]::new);

My advice would be to take the second column of the 2D array, and put it in its own integer array. 我的建议是获取2D数组的第二列,并将其放在自己的整数数组中。 Then, call Arrays.sort() on that array. 然后,在该数组上调用Arrays.sort() Finally, place the newly sorted array back into the 2D array as string values. 最后,将新排序的数组作为字符串值放回2D数组中。 Here is what it should look like, 这是它应该是什么样子,

int arr = new int[10];
String[][] copy = new String[10][2];
for(int i = 0; i < array.length; i++){
    arr[i] = Integer.parseInt(array[i][1]);
    System.arraycopy(array[i], 0, copy[i], 0, array[i].length);
}
Arrays.sort(arr);
for(int i = 0; i < array.length; i++){
    array[i][1] = String.valueOf(arr[i]);
}

//fixing the names
for(int i = 0; i < copy.length; i++){
    for(int j = 0; j < array.length; j++){
        if(copy[i][1] == array[j][1]){
             array[j][0] = copy[i][0];
             break;
        }
    }
}

EDIT: To address the order of the names, I changed the code to include a copy of the 2D array so that after rewriting the integer values in order, a check is done to see where each integer moved. 编辑:为了解决名称的顺序,我更改了代码以包含2D数组的副本,以便在按顺序重写整数值之后,进行检查以查看每个整数移动的位置。 For each integer, the corresponding name is transferred to where the integer moved. 对于每个整数,相应的名称将转移到整数移动的位置。

Loop over the array until its sorted and swap each time it's not. 循环遍历数组,直到它排序并每次都不交换。

public static void main(String[] args) {
    String[][] array = new String[4][2];
    array[0][0] = "Petter"; array[0][1] = "543";
    array[1][0] = "John";   array[1][1] = "276";
    array[2][0] = "Jay";    array[2][1] = "1879";
    array[3][0] = "Alf";    array[3][1] = "5021";

    System.out.println(Arrays.deepToString(array)); // [[Petter, 543], [John, 276], [Jay, 1879], [Alf, 5021]]

    sortArrayByScore(array);

    System.out.println(Arrays.deepToString(array)); // [[Alf, 5021], [Jay, 1879], [Petter, 543], [John, 276]]
}

public static void sortArrayByScore(String[][] array) {
    String tmpName, tmpScore;
    boolean sorted = false;

    while (!sorted) {
        sorted = true;
        for (int i = 0 ; i < array.length - 1 ; i++) {
            if (Integer.parseInt(array[i][1]) < Integer.parseInt(array[i+1][1])){
                sorted = false;
                // SWAP NAMES
                tmpName = array[i][0];
                array[i][0] = array[i+1][0];
                array[i+1][0] = tmpName;

                // SWAP SCORES
                tmpScore = array[i][1];
                array[i][1] = array[i+1][1];
                array[i+1][1] = tmpScore;
            }
        }
    }

}

Use a comparator to sort the items in an array. 使用比较器对数组中的项进行排序。 In your case you have an array of arrays so you need a comparator for an array. 在您的情况下,您有一个数组数组,因此您需要一个数组的比较器。 You can use a Comparator of String array which assumes the 2nd item is the value. 您可以使用String数组的比较器,该数组假定第二项是值。

public class SomeComparator implements Comparator<String[]> {
    /**
     * Assumes each row is length 2 and the 2nd String is really a number.
     */
    @Override
    public int compare(String[] row1, String[] row2) {
        int value1 = Integer.parseInt(row1[1]);
        int value2 = Integer.parseInt(row2[1]);
        // compare value2 first to sort descending (high to low)
        return Integer.compare(value2, value1);
    }
}

Then you can sort using Arrays.sort like this 然后你可以像这样使用Arrays.sort进行排序

String[][] data = newData(); // or however you get your data
Arrays.sort(data, new SomeComparator());

You can use a Comparator that sorts the inner String[] items on the Integer value of the second element, instead of using the default string sort: 您可以使用比较器对第二个元素的Integer值上的内部String []项进行排序,而不是使用默认的字符串排序:

Arrays.sort(array, (o1, o2) -> Integer.valueOf(o2[1]).compareTo(Integer.valueOf(o1[1])));

Here you are using lambda syntax to do the same as would be achieved by: 在这里,您使用lambda语法执行与以下操作相同的操作:

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(String[] o1, String[] o2) {
        return Integer.valueOf(o2[1]).compareTo(Integer.valueOf(o1[1]));
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM