Java Generic Comparator

Here is how you can write a generic comparator for your object, which can sort a list for a given field.
After reding the Overview I recommend checking the getMethod function first.


  • Interface – Implement the Comparator interface
  • Constructor – Save the field and order to sort(assuming all your class variables have getter methods)
  • getMethod – Since this is generic the type for the interface will be Object, but we can extract the methods from its Class
  • compare – Override the compare method, notice that all primitive types already implement comparable
  • read comments in code, Questions are welcome


Recent Posts

Recent Comments