Listutils.java---function class
Package com.enable.common.utils;
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;
/**
* @author Yinaibang
* In the list found in the database, it is often necessary to reorder the different fields. The general practice is to use a sorted field to re-query the database.
* If not the database query, directly in the first detected list in the sort, will undoubtedly improve the performance of the system. Here's a general way to sort the list,
*
* At least the following 5 points are required:
*
*①.list Element Object type arbitrary
*----> Use generic Solutions
*
*②. You can sort by any number of attributes of a list element object, that is, you can specify multiple attributes at the same time
*---> Solve with variable parameters of Java
*
The type of the *③.list element object property can be a number (byte, short, int, long, float, double, and so on, including positive, negative, 0), String (char, String), date (java.util.Date)
*---> For numbers: Uniform conversion to fixed-length string resolution, such as numbers 3 and 123, converted to "003" and "123", and then "15" and "7" converted to "015" and "007"
*---> For dates: You can first convert the date to a long type number, the number is resolved as above
*
The properties of the *④.list element object can have no corresponding getter and setter methods
*---> can use Java reflection to get property values for private and protected adornments
*
Each property of an object of the *⑤.list element object can be specified in ascending or descending order
*-With 2 overriding methods (one method satisfies all properties in ascending (descending) order, another method satisfies each attribute can be specified as ascending (descending))
*
*
*/
public class Listutils {
/**
* The list element is sorted by multiple attribute 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
* Property name of the list element
* @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.compareobject (Sortnamearr[i], ISASC, A, b);
if (0! = ret) {
Break
}
}
} catch (Exception e) {
E.printstacktrace ();
}
return ret;
}
});
}
/**
* Specify ascending or descending for each property of list
*
* @param list
* @param sortnamearr parameter array
* @param typearr for each property corresponding to the ascending ordinal group, in true order, false descending
*/
public static <E> void sort (list<e> List, final string[] Sortnamearr, final boolean[] Typearr) {
if (sortnamearr.length! = typearr.length) {
throw new RuntimeException ("The number of attribute array elements and the number of ascending ordinal group elements is not equal");
}
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.compareobject (Sortnamearr[i], typearr[i], A, b);
if (0! = ret) {
Break
}
}
} catch (Exception e) {
E.printstacktrace ();
}
return ret;
}
});
}
/**
* Sort 2 objects by the specified attribute name
*
* @param sortname
* Attribute Name
* @param ISASC
* True Ascending, False descending
* @param a
* @param b
* @return
* @throws Exception
*/
private static <E> int compareobject (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.length ());
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;
}
/**
* Assign 0 to the number object on the left by the specified length.
*
* Use case: Addzero2str (11,4) return "0011", Addzero2str ( -18,6) return "000018"
*
* @param numobj
* Digital Objects
* @param length
* The specified length
* @return
*/
public static String addzero2str (number numobj, int length) {
NumberFormat NF = numberformat.getinstance ();
Set whether to use grouping
Nf.setgroupingused (FALSE);
To set the maximum number of integer digits
Nf.setmaximumintegerdigits (length);
Set the minimum number of integer digits
Nf.setminimumintegerdigits (length);
Return Nf.format (numobj);
}
/**
* Gets the specified property value of the specified object (the limit for removing private,protected)
*
* @param obj
* The object where the property name resides
* @param fieldName
* Attribute 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 the property is private,protected decorated, it needs to be modified to be accessible.
Field.setaccessible (TRUE);
Object = Field.get (obj);
Restore the access properties of the Private,protected property
Field.setaccessible (accessible);
return object;
}
Object = Field.get (obj);
return object;
}
}
Userinfo.java
Package com;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
/**
*
* @author Yinaibang
*
*/
public class UserInfo implements Java.io.Serializable {
Private static final long serialversionuid = -3522051445403971732l;
Private Integer userId;
Private String username;
Private Date birthDate;
Private Integer age;
private float Frate;
Private char ch;
Public Date getbirthdate () {
return birthDate;
}
Public String Getbirthdatestr () {
SimpleDateFormat formater = new SimpleDateFormat ("Yyyy-mm-dd");
Return Formater.format (Getbirthdate ());
}
Public UserInfo (integer userId, String username, Date birthDate, integer age, float frate, char ch) {
Super ();
This.userid = userId;
This.username = Username;
This.birthdate = birthDate;
This.age = age;
This.frate = Frate;
this.ch = ch;
}
@Override
Public String toString () {
Return "UserInfo [userid=" + UserId + ", \tusername=" + Username + ", \tbirthdate=" + getbirthdatestr ()
+ ", \tage=" + Age + ", frate=" + Frate + ", ch=" + ch + "]";
}
}
Test class
Package com;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import java.util.List;
Import Com.enable.common.utils.ListUtils;
/**
*
* @author Yinaibang
*
*/
public class Test {
public static void Main (string[] args) throws Exception {
Test testobj = new test ();
list<userinfo> list = new arraylist<userinfo> ();
Public UserInfo (Integer userId, String username, Date Birthdate,integer, float frate, Char ch)
SimpleDateFormat formater = new SimpleDateFormat ("Yyyy-mm-dd");
UserInfo user1 = new UserInfo (3, "BBB", Formater.parse ("1980-12-01"), 1, 1.2f, ' a ');
UserInfo user2 = new UserInfo (0, "126", Formater.parse ("1900-10-11"), -3.6f, ' C ');
UserInfo User3 = new UserInfo ("5", Formater.parse ("1973-08-21"), 9.32f, ' f ');
UserInfo user4 = new UserInfo (465, "1567", Formater.parse ("2012-01-26"), 12.56f, ' 0 ');
UserInfo user5 = new UserInfo (2006, "&4m", Formater.parse ("2010-05-08"), 165.32f, ' 5 ');
UserInfo User6 = new UserInfo (5487, "hf67", Formater.parse ("2016-12-30"), 103, 56.32f, ' m ');
UserInfo user7 = new UserInfo (5487, "Jigg", Formater.parse ("2000-10-16"), 103, 56.32f, ' m ');
UserInfo User8 = new UserInfo (5487, "Jigg", Formater.parse ("1987-07-25"), 103, 56.32f, ' m ');
List.add (user1);
List.add (User2);
List.add (USER3);
List.add (USER4);
List.add (USER5);
List.add (USER6);
List.add (USER7);
List.add (User8);
System.out.println ("\ n-------Original sequence-------------------");
Testobj.printfuserinfolist (list);
Sort by UserID Ascending, username descending, birthdate ascending
String [] Sortnamearr = {"UserId", "username", "birthDate"};
Boolean [] Isascarr = {True,false,true};
Listutils.sort (List,sortnamearr,isascarr);
System.out.println ("\ n--------sorted in ascending order by UserID, username descending, birthdate ascending (if the userid is the same, then username descending, if username is the same, In birthdate Ascending)------------------");
Testobj.printfuserinfolist (list);
Sort in ascending order by UserID, username, birthdate
Listutils.sort (list, True, "userId", "username", "birthDate");
System.out.println ("\ n--------sorted by UserID, username, birthdate (if the userid is the same, then in username ascending, if username is the same, In birthdate Ascending)------------------");
Testobj.printfuserinfolist (list);
Sorted in reverse order by UserID and username
Listutils.sort (list, False, "userId", "username");
System.out.println ("\ n--------in reverse order of UserID and username (if the userid is the same, in reverse username)------------------");
Testobj.printfuserinfolist (list);
Sort in ascending order by username, birthdate
Listutils.sort (list, True, "username", "birthDate");
System.out.println ("\ n---------Press username, birthdate ascending (if username is the same, then birthdate Ascending)-----------------");
Testobj.printfuserinfolist (list);
Sort by birthdate reverse order
Listutils.sort (list, False, "birthDate");
System.out.println ("\ n---------birthdate in reverse order-----------------");
Testobj.printfuserinfolist (list);
Sort by Frate Ascending
Listutils.sort (list, True, "frate");
System.out.println ("\ n---------Press Frate ascending-----------------");
Testobj.printfuserinfolist (list);
Sort by ch in reverse order
Listutils.sort (list, False, "ch");
System.out.println ("\ n---------by CH reverse-----------------");
Testobj.printfuserinfolist (list);
}
private void Printfuserinfolist (list<userinfo> List) {
for (UserInfo user:list) {
System.out.println (User.tostring ());
}
}
}
The Java list is sorted by specifying multiple field properties for the element object