Java Comparator Example

June 30, 2009

Problem :

Java provides in built support for sorting a list of primitive types… with something like Collections.sort(list). Unfortunately things are not as simple for sorting a list of non-primitive types, since the java collections class doesn’t know exactly how to sort this type of list… let’s take Customer for an example….

Solution 1 :

1) Create a Comparator class for the desired entity.

2) Use this to show the Collections class, how the list is supposed to be sorted.

i.e. CustomerByNameComparator.java

...
public class CustomerByNameComparator implements Comparator<Customer>
{
     // compare(o1, o2) < 0     - o1 is less than o2
     // compare(o1, o2) == 0    - o1 is equal to o2
     // compare(o1, o2) > 0     - o1 is greater then o2
    public int compare(Customer o1, Customer o2) {
        return o1.getName().compareToIgnoreCase( o2.getName() );
    }
}

i.e.  Comparator class usage

...

// create a copy of the unsorted customer list
List<Customer> sortedCustomerList = unsortedCustomerList;

// using the comparator class, sort the customer list
Collections.sort( sortedCustomerList, new CustomerByNameComparator() );

...

Solution 2 :

1) Create a Comparator class for the desired entity.

2) Use this to create a TreeSet collection, sorted according to the comparator class.

ie. TreeSet collection example

...

// create a new treeset and instruct it on how to compare using above comparator
TreeSet<Customer> sortedCustomerList = new TreeSet( new CustomerByNameComparator() );

// add the unsorted collection to new treeset to sort customer list
sortedCustomerList.addAll( unsortedCustomerList );

...

Inshallah, that was not too complicated… Wa Allahu A’lam !!


package com.astra.customer.util;

import com.astra.customer.model.Customer;
import java.util.*;

public class CustomerByNameComparator implements Comparator<Customer>
{
// compare(o1, o2) < 0     – o1 is less than o2
// compare(o1, o2) == 0    – o1 is equal to o2
// compare(o1, o2) > 0     – o1 is greater then o2
public int compare(Customer o1, Customer o2) {
return o1.getName().compareToIgnoreCase( o2.getName() );
}
}

Entry Filed under: Java, Netbeans. Tags: , , , , , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Recent Comments

Categories

Top Posts

Links

Blog Stats

Meta