質問

I have a 2d array containing first name, last name, and a third irrelevant piece of data on each row. I need to alphabetize each row based on last name. How can I accomplish this?

I've tried using java.util.Arrays.sort(array[0]); but I can only get it to sort one row or one column. I need to keep the first name and last name together and sort by last name.

so say i have this array

String array [][]=new String[3][2];
       array[0][0]="Kyle";
       array[0][1]="Johnson";
       array[1][0]="Drew";
       array[1][1]="Anderson";
       array[2][0]="Jacob";
       array[2][1]="Peterson";

which is build like this

Kyle | Johnson

Drew | Anderson

Jacob| Peterson

and i need it to end up like this

Drew | Anderson

Kyle | Johnson

Jacob| Peterson

役に立ちましたか?

解決

You can use String.compareTo(String) to get the lexicographic ordering of 2 strings and formulate you own function to do that. The rules are simple (pseudo code):

be [s1,d1] // i.e s1 = Kyle, d1 = Johnson
be [s2,d2]
if (s1 < s2)  // means "Does s1 should come before s2 lexicographically" ie. s1.compareTo(s2) 
    [s1,d1] < [s2,d2]
else if (s1 > s2)
    [s2,d2] < [s1,d1]
else
    if (d1 < d2)
      etc...

see String.compareTo & String.compareToIgnoreCase to understand the return values of these methods

他のヒント

Here's a simple method that will sort 2D arrays. Pass in the index to use for sorting as second parameter. In your case it will be 1 as last name is indexed at 1.

I have omitted NULL check for brevity.

public static String[][] sort(String[][] array, final int sortIndex) {


        if (array.length < 2) {
            return array;
        }


        Arrays.sort(array, new Comparator<String[]>() {

            public int compare(String[] o1, String[] o2) {
                return o1[sortIndex].compareToIgnoreCase(o2[sortIndex]);
            }
        });

        return array;

    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top