Assume I have a user defined Java class called Foo such as:
public class Foo
{
private String aField;
@Override
public String toString()
{
The Java 8 version:
list.sort(Comparator.comparing(Object::toString));
Or streaming:
List<Foo> sortedList = unsortedList
.stream()
.sorted(Comparator.comparing(Object::toString)))
.collect(Collectors.toList());
lambdaj allows you to sort, filter and in general manipulate collections without writing loops or obscure inner classes. For example the sorting you were asking can be achieved as it follows:
sort(foos, on(Foo.class).toString());
If you are interested in it check it out at:
http://code.google.com/p/lambdaj/
I would strongly advise you to only use toString for debugging purposes... however... to expand on what Yuval A wrote above...
public class X implements Comparator { public int compare(final Foo a, final Foo b) { return (a.toString().compareTo(b.toString())); } }
However you really should have Foo implement Comarable or write a proper Compartor that does not make use of toString.
I would do something very similar to Pierre:
public class Foo implements Comparable<Foo>
{
private String aField;
@Override
public String toString()
{
return aField;
}
public int compareTo(Foo o)
{
return this.toString().compareTo(o.toString());
}
}
Then, like Pierre, I would use Collections.sort(list)
as Pierre suggests.