Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetically Sort a Java Collection based upon the 'toString' value of its member items

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?

like image 452
Tom Neyland Avatar asked Feb 16 '09 22:02

Tom Neyland


2 Answers

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.

like image 172
Dan Dyer Avatar answered Oct 05 '22 03:10

Dan Dyer


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.

like image 29
Yuval Adam Avatar answered Oct 05 '22 03:10

Yuval Adam