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).
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]
*/
}
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With