Alphabetically Sort a Java Collection based upon the 'toString' value of its member items
Collections.sort(fooList,
new Comparator<Foo>()
{
public int compare(Foo f1, Foo f2)
{
return f1.toString().compareTo(f2.toString());
}
});
Assuming that toString never returns null and that there are no null items in the list.
Use the API sort(List list, Comparator c)
which specifies a comparator, and implement is as you wish.
Alternatively, if you do not specifically need a List, use a SortedSet
, same goes with the comparator.
google-collections makes this really easy with Ordering:
Collections.sort(list, Ordering.usingToString());
Is bringing in a whole 3rd-party library just to use something you could write trivially using a Comparator (as others have provided) worthwhile? No, but google-collections is so cool you'll want to have it anyway for a bunch of other reasons.
On the sorting front, you can also easily do things like reversing:
Ordering.usingToString().reverse();
or break ties:
Ordering.usingToString().compound(someOtherComparator);
or deal with nulls:
Ordering.usingToString().nullsFirst();
etc., but there's a bunch more stuff in there (not just sorting-related, of course) that leads to really expressive code. Check it out!