Java – Alphabetically Sort a Java Collection based upon the ‘toString’ value of its member items

collectionsjavasorting

Assume I have a user defined Java class called Foo such as:

public class Foo 
{

    private String aField;

    @Override
    public String toString()
    {
        return aField;
    }

}

And a Collection such as:

List<Foo> aList;

What I am looking to do is to sort the List alphabetically based upon each member's returned '.toString()' value.

I have tried using the Collections.sort() method, but the result was not what I was attempting.
What do I need to do inorder to accomplish this?

Best Solution

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.