How to compare and sort objects by property (using customized comparator)

Example: sort a bank account by its balance


public class BankAccount implements Comparable<BankAccount> {
	
	int accountNo;
	double balance;
	
	public BankAccount(int an, double b)
	{
		this.accountNo = an;
		this.balance = b;
	}
	
	public void setBalance(double b)
	{
		this.balance = b;
	}
	
	public double getBalance()
	{
		return this.balance;
	}
	@Override
	public int compareTo(BankAccount arg0) {
		// TODO Auto-generated method stub
		return (int) (this.getBalance() - arg0.getBalance());
		//return + if this is greater, other wise -, 0 if this = arg0
	}

}

//main program
import java.util.ArrayList;
import java.util.Collections;


public class BankAccountTester {
	
	public static void main (String[] args)
	{
		final int NO_OF_ACCOUNTS = 10;
		ArrayList<BankAccount> bankAccountList = new ArrayList<BankAccount>();
		
		//generate some bank account with random balance and add to the arraylist of bankaccount
		for (int i = 0; i < NO_OF_ACCOUNTS; i++)
		{
			bankAccountList.add(new BankAccount(i, Math.random()*1000));
		}
		
		//using the natual compareTo method in bankAccountList to sort
		Collections.sort(bankAccountList);
		/*Can also use external comparator method, which is more flexiable, meaning you can compare any two objects without modifying the source code even if they are not comparable */
		/*
		Collections.sort(bankAccountList, new Comparator<BankAccount>() {
		    public int compare(BankAccount one, BankAccount other) {
		        return (int)(one.getBalance()- other.getBalance());
		    }
		});
		*/
		
		for (BankAccount b : bankAccountList)
		//read as for every bankAccount b in the bankAccountList
		{
			System.out.println("Accout No." + b.getAccountNo() + " Balance :" + b.getBalance()); 
		}
	}
}

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