METS BLOG

METS BLOG

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.

Overview

  • 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

Usage


3 responses to “Java Generic Comparator”

  1. […] Here is an example of sorting a table with ajax. I’m using using a generic comparator which I implmented a while ago to sort the list items, it saves me few lines of code actually. If you are intrested in the generic comparator […]

  2. Verry good information. Luky mme I came across your blog by chance (stumbleupon).
    I have bookmarked it for later!

  3. Imteyaz Ahmed says:

    Great ! its so easy to understand..

Leave a Reply

Your email address will not be published. Required fields are marked *