Posted in Software Engineering

How to sort a List of Bean in java

Let say we have a List object declared as the following:

class Bean {

private String name;

private Integer identityNo;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getIdentityNo() {

return identityNo;

}

public void setIdentityNo(Integer identityNo) {

this.identityNo = identityNo;

}

}

and then in the main class we have:

List<Bean> listBean = new ArrayList<Bean>();

How do we sort listBean ?

There are 2 ways to sort listBean using a standard Java library:

1. Implements Comparable in the class Bean and then call Collections.sort :

class Bean implements Comparable<Bean> {

@Override

public int compareTo(Bean otherObject) {

return getIdentityNo().compareTo(otherObject.getIdentityNo());

}

}

Collections.sort(listBean);

2. Using Collection only:

Collections.sort(listBean, new Comparator<Bean>() {

@Override

public int compare(Bean b1, Bean b2)

{

return b1.getIdentityNo().compareTo(b2.getIdentityNo());

}

});

Personally I would prefer to use the 2nd method.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s