Generic Comparator in Java

Generic Comparator in JavaGeneric Comparator in Java Collections, from word itself describes the purpose of it. I ran into the need of one generic comparator which I could use for storing POJO in the List and developed the generic comparator Class which could be used with Collections.sort() method in Java; to sort a List of values in ascending or descending order.  This class support following data types Integer, String, Long, Double, Float, Date in the POJO can be sort effectively.

For Example: List of Objects scenario

Let’s say, we have a Class called PersonVO, it has 6 attributes in it –

And using above PersonVO Class defining List a objects

In typical scenario you may have to write multiple comparator class for each data type and based attribute you have to supply specific comparator to achieve sorting for each column in your Application.  Now, Question for you?

How to sort multiple columns with Single Comparator based on specific attribute & specific need?

Here it comes answer to above question; make use of in your application to achieve sorting need dynamically.  I’m going to describe, how to use and execution with sample output.

How to use:

Download from GitHub repo and place the Java file into your project.  Now you can take advantage in two ways:

Usage 1

For List for objects and sorting underneath object attribute value (for e.g. persons list object)

Usage 2

For List of values defined using above defined data types

That’s all, its easy to use ‘Generic Comparator in Java’!

Docs & Downloads

Javadoc: and Sample Demo Project  genericComparator you can git clone from GitHub.

Execution Output of

If you have queries, leave a comment!