0

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

  • 1
    _alphabetize_ ? can you please post the sample data – jmj Feb 15 '12 at 05:47
  • 1
    [What have you tried so far??](http://mattgemmell.com/2008/12/08/what-have-you-tried) – Fahim Parkar Feb 15 '12 at 05:50
  • not at all... why?? my link tell what should be provided when we ask something... – Fahim Parkar Feb 15 '12 at 05:54
  • I think this is what you want....http://stackoverflow.com/questions/4907683/sort-a-two-dimensional-array-based-on-one-column – Shashank Kadne Feb 15 '12 at 05:55
  • How are you generating this Array? I think that you might want to create a POJO with three members, then add pojos to an array or list and then implement a custom comparator for Arrays.sort or Collections.sort – Sap Feb 15 '12 at 06:45

2 Answers2

1

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;

    }
anzaan
  • 245
  • 1
  • 5
0

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

Boaz
  • 4,549
  • 2
  • 27
  • 40
  • Cool this looks like what I need, One question. How can I get it to ignore case? Edit* Quick google search turned up .compareToIgnoreCase(), Thanks! – user1210559 Feb 15 '12 at 07:24
  • I've actually linked it inside the answer... look at the line under the code segment :) – Boaz Feb 15 '12 at 13:00