You can do that, a well known example is the Comparator<T> interface.
For example:
List<Person> persons = personDAO.list();
Collections.sort(persons, new Comparator<Person>() {
// Anonymous inner class which implements Comparator interface.
public int compare(Person one, Person other) {
return one.getName().compareTo(other.getName());
}
});
Some may argue against this and tell that it rather belongs in the Person class, so that you don't need to implement it again and again whenever needed. E.g.
public class Person {
// ...
public static final Comparator<Person> ORDER_BY_NAME = new Comparator<Person>() {
public int compare(Person one, Person other) {
return one.getName().compareTo(other.getName());
}
};
}
which can be used as follows:
Collections.sort(persons, Person.ORDER_BY_NAME);