Alex Rivera | Logout

Sort ArrayList of Array in Java

Asked 2011-01-15T13:27:30.200
14

What is the best way to sort an ArrayList<String[]> in Java?

Where String[] is...

String[] strAarray = new String[] { "abc", "abc", "abc", "abc", "abc", "abc", "abc" };

Now I want to sort the whole ArrayList by the 2nd value of String[] (at index 1). I need to loop through each and every String[] and then its child at index 1.

Any ideas?

Edit:


I have more descriptions. I am actually getting schools from some XML file and every node in XML has 7 attributes. Now I am creating an ArrayList of String[] which is holding those school nodes from XML and String[] strArray itself is holding attributes of particular node.

Now, the way I want to sort it is, it should sort according to State of school which is the 2nd attribute in XML and index 1 in String[] inside ArrayList.

I need to loop through each and every School first (node in XML, String[] in Java) and then I will have to filter State (State attribute in XML, String[1] in Java).

Edit
Report

2 Answers

36

Start with Collections.sort, the one that takes a custom Comparator. You'll need to write a custom Comparator for this also.

For instance, assuming you want to rely on the natural ordering of Strings as defined in their compareTo method:

public static void main(String[] args) throws Exception {
        ArrayList<String[]> listOfStringArrays = new ArrayList<String[]>();
        listOfStringArrays.add(new String[] {"x","y","z"});
        listOfStringArrays.add(new String[] {"a","b","c"});
        listOfStringArrays.add(new String[] {"m","n","o"});
        Collections.sort(listOfStringArrays,new Comparator<String[]>() {
            public int compare(String[] strings, String[] otherStrings) {
                return strings[1].compareTo(otherStrings[1]);
            }
        });
        for (String[] sa : listOfStringArrays) {
            System.out.println(Arrays.toString(sa));
        }
        /* prints out 
          [a, b, c]
          [m, n, o]
          [x, y, z]
        */ 

    }
answered 2011-01-15T13:34:45.037
3

You write a Comparator that compares two String[] by the correct child, and then you pass it to Collections.sort(List<T> list, Comparator<? super T> c).

answered 2011-01-15T13:32:36.643

Your Answer