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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With