What is the best way to sort an ArrayList in Java?
Where String[] is...
String[] = new String[] { \"abc\", \"abc\", \"ab
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 listOfStringArrays = new ArrayList();
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() {
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]
*/
}