Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ArrayList of Array in Java

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).

like image 535
Umair A. Avatar asked Jan 15 '11 13:01

Umair A.


3 Answers

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]
        */ 

    }
like image 147
whaley Avatar answered Nov 02 '22 07:11

whaley


You create a Comparator<String[]> like so:

new Comparator<String[]>() {
  public int compare(String[] first, String[] second) {
    return first[1].compareTo(second[1]);
  }
}

then pass it to Collections.sort().

You might want to do some checking if the second element is actually present in the array. You could also do a custom comparison if the standard String comparison isn't enough.

like image 26
Jorn Avatar answered Nov 02 '22 07:11

Jorn


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).

like image 40
Paul Tomblin Avatar answered Nov 02 '22 07:11

Paul Tomblin