Use Commons-beanutils to sort multiple properties in a list element in Java

Source: Internet
Author: User
Tags sort

The

Commons-beanutils class Library has a Beancomparator class that can be used to sort JavaBean. But this class can only sort on one property at a time. Here is an example of using Beancomparator to sort multiple properties of JavaBean, very simple:

 1.import Org.apache.commons.beanutils.BeanComparator;
2.import java.util.Collections;
3.import Java.util.Comparator;
4.import java.util.List; 5.6./** 7. * Class 8 that sorts multiple properties of a List element. 
* * 9 @SuppressWarnings ({"Unchecked"}) 10.public class Listsorter {11.     12./** 13. * Multiple properties of the List element are sorted.     For example Listsorter.sort (list, "name", "Age"), press 14 first.
* The Name property is sorted, and the element with the same name is sorted by the age attribute.     15. * 16.     * @param list contains list 17 of the elements to be sorted. * @param properties to sort.
The preceding values have high precedence.    18. * * 19.        public static <V> void sort (list<v> List, Final String ... properties) {20.            Collections.sort (list, new comparator<v> () {21.                public int Compare (v O1, v O2) {22.
if (O1 = = null && O2 = null) return 0;
if (O1 = null) return-1;
if (O2 = null) return 1;                25.26.                    for (String property:properties) {27.
Comparator C = new Beancomparator (property);              28.      int result = C.compare (O1, O2);                        If (Result!= 0) {30.
return result;                31.} 32.                } 33.
return 0;        34.} 35.
}); .} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.