Home > Enterprise >  Sorting 2d String array using java
Sorting 2d String array using java

Time:03-17

I am trying to sort a string 2d array taken as user input. But this code is working for some cases and not working for some.

The code is:

 public class Source {
    public static void main(String args[]) throws Exception {
        Scanner sc = new Scanner(System.in);
        String[][] customerDetails= new String[5][3];
        customerDetails[0][0]="10";
        customerDetails[0][1]="Raj";
        customerDetails[0][2]="Chennai";
  
        customerDetails[1][0]="100";
        customerDetails[1][1]="Akshay";
        customerDetails[1][0]="Pune";

        customerDetails[2][0]="20";
        customerDetails[2][1]="Simrath";
        customerDetails[2][2]="Amristar";

        customerDetails[3][0]="30";
        customerDetails[3][1]="Gaurav";
        customerDetails[3][2]="Delhi";

        customerDetails[4][0]="101";
        customerDetails[4][1]="Ganesh";
        customerDetails[4][2]="Chennai";

    
        
        /*for (int i = 0; i < 5; i  ) {
            for (int j = 0; j < 3; j  ) {
                //customerArray[i][j] = sc.nextLine();
            }
        }*/

        Arrays.sort(customerArray, (a, b)->a[0].compareTo(b[0]));
        
        for (int y = 0; y < 5; y  ) {
            for (int z = 0; z < 3; z  ) {
                System.out.println(customerArray[y][z]);
            }
        }
    }
}

I have given direct inputs in this code. I want to sort the numbers as String

CodePudding user response:

You are getting wrong answer because you were comparing 0th index of each row of 2D array which are String. So, according to string comparison logic the outputs are correct. To get the sorting order as integer, you have to convert 0th index of each row to Integer in your comparator.

Modify your sort method call like below which should work according to your expectation because a[0] and b[0] are converted to Integer before comparison:

Arrays.sort(customerArray, (a, b)->Integer.valueOf(a[0]).compareTo(Integer.valueOf(b[0])));

Output:

10
Akhil
Pune
20
Rajni
Hyderabad
30
Praveen
Delhi
100
Rohith
Chennai
101
Sam
Bangalore
  • Related