简体   繁体   中英

Sorting String[][] unexpected output

I want to sort my String[][] with respect to second column. I tried this

public static String[][] sorting_minn(String[][] list){ 
    double[] temp = new double[list.length];
    String[][] tempf = list;

    if(list[1][1]!=null){
    for(int i = 0; i<list.length; i++){
        if(list[i][2]==null){
            break;

        } else {
            temp[i]=Double.parseDouble(list[i][2]);


        }

    }

Arrays.sort(temp);

for(int f = 0; f<list.length-1;f++){
    for(int m = 0; m<list.length;m++){
        if(list[m][2]!=null && Double.parseDouble(list[m][2])==temp[f]){
             for(int n = 0; n<4; n++){
                 tempf[list.length-f-1][n]=list[m][n];

             }
        m = list.length;
            }
        }

    }
}
return tempf;

}

As an output I get this: 产量 . I need suggestion on how to improve this code.

try something like:

        Arrays.sort(list, new Comparator<String[]>() {
            @Override
            public int compare(String[] o1, String[] o2) {
                String left = o1[1]!=null ? o1[1] : "";
                String right = o2[1]!=null ? o2[1] : "";
                return left.compareTo(right);
            }
        });

this treats nulls as empty strings, and exploits the fact that strings are comparable, although lexicographic. if you want the reverse order just do this instead:

right.compareTo(left)

if you want integer ordering you could parse an Integer out of both sides (Integer.MIN for null) and compare 2 Integers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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