Assume I have a user defined Java class called Foo such as:
public class Foo
{
private String aField;
@Override
public String toString()
{
If you want the collection to remain sorted, rather than sorting it at specific points, you could put it in a TreeSet with a defined Comparator. Otherwise, I'd use the Collections.sort method already mentioned by Yuval.
Collections.sort(myPojoList, (a, b) -> a.getId() - b.getId()); //ASC
Collections.sort(myPojoList, (a, b) -> b.getId() - a.getId()); //DESC
//Alternatively use Integer.compare()
Collections.sort(myPojoList, (a, b) -> Integer.compare(a.getId(), b.getId())); //ASC
Collections.sort(myPojoList, (a, b) -> Integer.compare(b.getId(), a.getId())); //DESC
Collections.sort(myPojoList, (a, b) -> a.getName().compareTo(b.getName())); //ASC
Collections.sort(myPojoList, (a, b) -> b.getName().compareTo(a.getName())); //DESC
Collections.sort(myPojoList, (a, b) -> Boolean.compare(a.isMale(), b.isMale())); //ASC
Collections.sort(myPojoList, (a, b) -> Boolean.compare(b.isMale(), a.isMale())); //DESC
myPojoList= new ArrayList<>(new LinkedHashSet<>(myPojoList)); //Distinct
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.
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.
public class Foo
implements Comparable<Foo>
{
private String aField;
public Foo(String s)
{
aField=s;
}
public String getAField()
{
return aField;
}
public int compareTo(Foo other)
{
return getAField().compareTo(other.getAField());
}
@Override
public String toString()
{
return getAField();
}
}
and then
Collections.sort(list);
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!