0

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: output . I need suggestion on how to improve this code.

5
  • Could you add the desired output? Commented Dec 31, 2012 at 14:07
  • 2
    So that you are aware; the second column is located at index [1] not index [2]. Commented Dec 31, 2012 at 14:08
  • @NominSim I'm aware of that. Commented Dec 31, 2012 at 14:09
  • Already answered here? stackoverflow.com/questions/4907683/… Commented Dec 31, 2012 at 14:09
  • @11684 the desired output would be basiacally the same table but with last three rows entries left null; Commented Dec 31, 2012 at 14:11

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.