Java tool class for the list collection to sort by one or more attributes of a collection element object

Source: Internet
Author: User

Tag:length   long   amp   max    Access     .text   trace   final   null   

Import Java.lang.reflect.field;import Java.text.numberformat;import Java.util.collections;import      Java.util.comparator;import Java.util.date;import Java.util.list;public class Listutils {/** * The elements of the List are sorted by multiple property names,     * The properties of the list element can be numbers (byte, short, int, long, float, double, etc., support positive, negative, 0), Char, String, java.util.Date * * @param lsit  * @param sortname * List Element property name * @param Isasc * True Ascending, False descending */public static  <E> void sort (list<e> list, final Boolean isasc, Final String ... sortnamearr) {Collections.sort (list,                New Comparator<e> () {public int compare (e A, E b) {int ret = 0; try {for (int i = 0; i < sortnamearr.length; i++) {ret = Listutils.compareo                        Bject (Sortnamearr[i], ISASC, A, b);                        if (0! = ret) {break; }}} catch (Exception e) {e.printstacktrace ();            } return ret;    }        }); /** * For each property of the list is specified ascending or descending * @param list * @param sortnamearr parameter array * @param typearr for each property Array, True ascending, false descending */public static <E> void sort (list<e> List, final string[] Sortnamearr, Final Boole An[] Typearr {if (sortnamearr.length! = typearr.length) {throw new RuntimeException ("attribute array element number and ascending ordinal group element        Number is not equal "); } collections.sort (list, new comparator<e> () {public int compare (e A, E b) {int r                ET = 0; try {for (int i = 0; i < sortnamearr.length; i++) {ret = Listutils.compareo                        Bject (Sortnamearr[i], typearr[i], A, b);                        if (0! = ret) {break; }}} catch (Exception e) {E.printStackTrace ();            } return ret;    }        }); }/** * Sorts 2 objects by the specified property name * * @param sortname * Property name * @param ISASC * TR UE Ascending, False Descending * @param A * @param b * @return * @throws Exception */private static <E> int Co        Mpareobject (Final String sortname, final Boolean isasc, e A, E B) throws Exception {int ret;        Object value1 = Listutils.forcegetfieldvalue (A, sortname);        Object value2 = Listutils.forcegetfieldvalue (b, sortname);        String str1 = value1.tostring ();        String str2 = value2.tostring (); if (value1 instanceof number && value2 instanceof number) {int maxlen = Math.max (Str1.length (), STR2.L            Ength ());            STR1 = Listutils.addzero2str ((number) value1, maxlen);        STR2 = Listutils.addzero2str ((number) value2, maxlen);          } else if (value1 instanceof date && value2 instanceof date) {  Long time1 = ((Date) value1). GetTime ();            Long time2 = ((Date) value2). GetTime ();            int maxlen = long.tostring (Math.max (time1, time2)). Length ();            STR1 = Listutils.addzero2str (time1, MaxLen);        str2 = Listutils.addzero2str (time2, MaxLen);        } if (ISASC) {ret = Str1.compareto (STR2);        } else {ret = Str2.compareto (STR1);    } return ret;     /** * gives the number object a specified length of 0 on the left.  * Use case: Addzero2str (11,4) return "0011", Addzero2str ( -18,6) return " -000018" * * @param numobj * Digital Object * Length of @param * specified * @return * */public static String addzero2str (number numobj, int length)        {NumberFormat NF = numberformat.getinstance ();        Sets whether to use grouping nf.setgroupingused (false);        Sets the maximum integer number of digits nf.setmaximumintegerdigits (length);        Sets the minimum number of integer digits nf.setminimumintegerdigits (length);    Return Nf.format (numobj); }/** * Gets the specifiedThe specified attribute value of the image (the limit for removing private,protected) * * @param obj * Property name of the object * @param fieldName * Property name * @return * @throws Exception */public static object Forcegetfieldvalue (Object obj, String fieldName        ) Throws Exception {Field field = Obj.getclass (). Getdeclaredfield (FieldName);        Object object = null;        Boolean accessible = Field.isaccessible ();            if (!accessible) {//If it is a private,protected decorated property, it needs to be modified to be accessible field.setaccessible (true);            Object = Field.get (obj);            The Access property of the Restore Private,protected property field.setaccessible (accessible);        return object;        } object = Field.get (obj);    return object; }}

Java Tool class about a list collection that is sorted by one or more properties of a collection element object

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.