Suppose I have a Record
class with a String name
(could be any other type) attribute. In another class I have a method order(List<Record>)
which needs to sort the list by name
. To do this, I want to create a custom stateless Comparator
. I have seen three options that are commonly used:
Static comparator
private static final Comparator<Record> STATIC_COMPARATOR = new StaticComparator(); private static class StaticComparator implements Comparator<Record> { @Override public int compare(Record m1, Record m2) { return m1.getName().compareTo(m2.getName()); } } void order(List<Record> records) { records.sort(STATIC_COMPARATOR); }
Singleton comparator
private static enum SingletonComparator implements Comparator<Record> { INSTANCE; @Override public int compare(Record m1, Record m2) { return m1.getName().compareTo(m2.getName()); } } void order(List<Record> records) { records.sort(SingletonComparator.INSTANCE); }
Use
Comparator.comparing()
void order(List<Record> records) { records.sort(Comparator.comparing(Record::getName)); }
Assuming order()
gets called a lot, what are the tradeoffs for each approach? How do they compare on matters such as serialization, thread safety, and performance?