Monday, September 22, 2014

Inline Comparator Example

Here's an example of using an inline comparator in java.

To sort a list of Person objects according to its 'name' property, use the template below.

List personList = personListDTO.getPersons();
Collections.sort(personList ,new Comparator() {
   public int compare(Object o1, Object o2) {
    Person p1 = (Person)o1;
    Person p2 = (Person)o2;
    return p1.getName().compareTo(p2.getName());
   }
  });

You may also use the more compact form below.

List<Person> personList = personListDTO.getPersons(); 
Collections.sort(personList ,new Comparator<Person>() {
 public int compare(Person p1, Person p2) {
  return p1.getName().compareTo(p2.getName());
 }
}); 

This code will help you avoid getting a warning in eclipse of the generic type -

- Type safety: The expression of type new Comparator(){} needs unchecked conversion to conform to Comparator<? super Person>
- Type safety: Unchecked invocation sort(List<Person>, new Comparator(){}) of the generic method sort(List<T>, Comparator<? super T>) of type Collections
- Comparator is a raw type. References to generic type Comparator<T> should be parameterized 

Related Links:
More examples on using Comaparator in Java
How to sort a map in Java

Reference:
Collections class reference


No comments:

Post a Comment