Apache BeanComparator Tips

Null排序處理:Null > Non-Null (default)

new BeanComparator(“Bean的Attribute Name”, new NullComparator());

new BeanComparator([Bean的Attribute Name], NullComparator(true));

Null排序處理:Null < Non-Null

new BeanComparator([Bean的Attribute Name], NullComparator(false));

排序:A → Z,ASC小到大,升冪

chain.addComparator(BeanComparator物件);

chain.addComparator(BeanComparator物件, false);

排序:Z → A,DESC,大到小,降冪

chain.addComparator(BeanComparator物件, true);

多欄排序(含Null值):依id、name順序,由小到大排列,Null值排在最後面

List<MyObject> results = new ArrayList<MyObject>();

……

ComparatorChain chain = new ComparatorChain();

// Null > Non-Null

BeanComparator com = new BeanComparator(“id”,new NullComparator());

// A → Z → Null

chain.addComparator(com);

chain.addComparator(new BeanComparator(“name”,new NullComparator()));

Collections.sort(results, chain);

多欄排序(含Null值):依id、name順序,由大到小排列,Null值排在最前面

List<MyObject> results = new ArrayList<MyObject>();

……

ComparatorChain chain = new ComparatorChain();

// Null > Non-Null

BeanComparator com = new BeanComparator(“id”,new NullComparator());

// Null → Z → A

chain.addComparator(com, true);

chain.addComparator(new BeanComparator(“name”,new NullComparator()), true);

Collections.sort(results, chain);

※如果沒有加NullComparator處理,會出現NullPointerException的錯誤

 

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