Skip to main content

Sorting Collections of Pojo Classes with Generic Comparator

Posted by HRgiger on June 4, 2012 at 3:34 AM PDT


If you want to sort your Pojo classes via specific field probably you are facing issues like me. . But first of all lets review possible ways of sorting collections. Most simplier way to do that "Collections.sort(...); " or "Arrays.sort(...); " methods. Methods takes an argument and if the argument class implements Comparable interface then its returns a logical result. Java types suitable for sorting. But what about special POJO classes which you have implemented? Lets say you have list of "Stormtrooper" object for your universe and if you try to sort your objects you will be facing lovely exceptions from compiler. Because java.util.Collections or java.util.Arrays classes has no idea how to sort Stormtroopers and it needs little bit help from you. So lets see how to achieve that problem.