What is the best way to sort an ArrayList
in Java?
Where String[] is...
String[] = new String[] { \"abc\", \"abc\", \"ab
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)
.
Use TreeSet or TreeMap http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html
Suppose we have a list of arrays [["x", "y","z"], ["a", "b", "c"], ["m", "n", "o"]]
We can use list.sort() instead of Collections.sort().
To sort, we can adopt a cleaner way using lambdas and method references.
Using lambda:
listOfStrings.sort((a, b)->a[1].compareTo(b[1]));
Using method reference:
listOfStrings.sort(Comparator.comparing(a->a[1]));
Outputs:
[a, b, c]
[m, n, o]
[x, y, z]
This is extremely easy to do with Java 8. Just write:
list.sort(Comparator.comparing(a -> a[1]));
For example, the following code:
List<String[]> list = Arrays.asList(
new String[] { "abc", "abc", "abc", "abc", "abc", "abc", "abc" },
new String[] { "xyz", "xyz", "xyz", "xyz", "xyz", "xyz", "xyz" },
new String[] { "fgh", "fgh", "fgh", "fgh", "fgh", "fgh", "fgh" });
list.sort(Comparator.comparing(a -> a[1]));
list.stream().map(Arrays::toString).forEach(System.out::println);
Will yield the wanted result:
[abc, abc, abc, abc, abc, abc, abc]
[fgh, fgh, fgh, fgh, fgh, fgh, fgh]
[xyz, xyz, xyz, xyz, xyz, xyz, xyz]
Based on your edit: Your String[] should be a School object to contain your attributes. Make your School object implement Comparable and that will allow easy sorting with Collections.sort().
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]
*/
}