Monthly Archives: March 2013

Using Comparator Interface to sort an object list

The Comparator interface exists in JDK since version 1.2 so it’s a mature part of Java tool box. And it’s a useful Interface. It provides two methods: compare and equals. We can use these methods when we’d like to sort an Array or Collection. Wicked.

So let’s sort a List with full of Object references.

Need a POJO like this:

Beer
-name
-strong

And the task is we’d like to have the strongest beer because we haven’t got enough time so you know. This case we need a Comparator for the stength of beer:

class BeerStrongComparator implements Comparator<Beer> {

  public int compare(Beer b1, Beer b2) {
    return b1.getStrong() < b2.getStrong() ? -1
     : b1.getStrong() > b2.getStrong() ? 1 : 0;
  }

}

And finally the usage:

  Collections.sort(allBeersList, new BeerStrongComparator());

You just put the Comparator as a second parameter in Collections class sort static method.

Tagged , ,