Java: Sorting a Collection of objects using your own criteria

How to sort a Collection of objects using your own criteria:

Collection<Account> accountList = getAccountList();
List accountListSorted = new ArrayList(accountList);
Collections.sort(accountListSorted, new AccountComparator());

Here is a Comparator implementation using the alphabetical order, but you could decide to sort your objects by date, balance, or whatever you might need:

public class AccountComparator implements java.util.Comparator
{
    public AccountComparator()
    {
    }

    public int compare(Object arg0, Object arg1)
    {
        Account a1 = (Account) arg0;
        Account a2 = (Account) arg1;
        return a1.getFirstName().compareTo(a2.getFirstName());
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: