General method for sorting List objects
General method for sorting List objects
Different fields are usually re-ordered in the list found in the database. Generally, sort fields and re-query them in the database. If the database query is not found, it is directly sorted in the list obtained for the first time, which will undoubtedly improve the system performance.
As long as you store the results obtained for the first time in the session, you can re-sort the list. Collections. sort (list) can be used to sort lists. However, this method does not work if the list contains an object. How can we sort them? If there is a UserInfo object that contains the following fields:
Private java. lang. Integer userId;
Private java. lang. String username;
Private java. util. Date birthDate;
Private java. lang. Integer age;
To sort userids, you may use the following method:
Collections.sort(list, new Comparator() { public int compare(Object a, Object b) { int one = ((Order)a).getUserId (); int two = ((Order)b).getUserId (); return one- two ; } }); In this way, if you want to sort the fields in the UserInfo list, do you want to write the code shown above for each field? That is certainly not the result we need. Write programs must be more refined and not more redundant. Can I write a general method? The answer is yes, but the following three problems must be solved first:
1. You can use generics;
2. General comparison methods such as compareTo can be used;
3. Are there any generic methods like generic and generic methods?
1st problems can be solved, and 2nd problems are not very difficult, because all Java types are inherited from objects and there is a ToString method, at present, all types can be converted to String, and then compared with compareTo. 3rd problems. We have not yet found the generic method we need. But can we use the getMethod and invoke methods to Dynamically Retrieve them. The complete code is as follows:
Public class SortList
{Public void Sort (List
List, final String method, final String sort) {Collections. sort (list, new Comparator () {public int compare (Object a, Object B) {int ret = 0; try {Method m1 = (E) ). getClass (). getMethod (method, null); Method m2 = (E) B ). getClass (). getMethod (method, null); if (sort! = Null & "desc ". equals (sort) // reverse ret = m2.invoke (E) B), null ). toString (). compareTo (m1.invoke (E) a), null ). toString (); else // forward ret = m1.invoke (E) a), null ). toString (). compareTo (m2.invoke (E) B), null ). toString ();} catch (NoSuchMethodException ne) {System. out. println (ne);} catch (IllegalAccessException ie) {System. out. println (ie);} catch (InvocationTargetException it) {System. out. println (it) ;}return ret ;}});}}
Check whether the above Code has successfully solved the above three problems and added a forward and reverse order. No specific object or type is used in the code, and it is universal. We use a generic E. If you want to sort the userId of UserInfo, the method name can be passed in as a string with parameters, for example, "getUserId ". You can use the Code provided below to test it:
// Test. javapackage test; import java. util. arrayList; import java. util. list; import java. text. simpleDateFormat; public class Test {public static void main (String [] args) throws Exception {List
List = new ArrayList
(); SimpleDateFormat formater = new SimpleDateFormat ("yyyy-MM-dd"); list. add (new UserInfo (3, "B", formater. parse ("1980-12-01"), 11); list. add (new UserInfo (1, "c", formater. parse ("1980-10-01"), 30); list. add (new UserInfo (2, "a", formater. parse ("1973-10-01"), 11); System. out. println ("------- original sequence -------------------"); for (UserInfo user: list) {System. out. println (user. toString ();} // call the sort generic class SortList
SortList = new SortList
(); // Sort by userId sortList. sort (list, "getUserId", "desc"); System. out. println ("-------- by userId Reverse Order ------------------"); for (UserInfo user: list) {System. out. println (user. toString ();} // sort sortList by username. sort (list, "getUsername", null); System. out. println ("--------- sort by username -----------------"); for (UserInfo user: list) {System. out. println (user. toString ();} // sort sortList by birthDate. sort (list, "getBirthDatestr", null); System. out. println ("--------- sort by birthDate ---------------"); for (UserInfo user: list) {System. out. println (user. toString ());}}}
The test results are as follows:
------- Original sequence -------------------
3; B; 1980-12-01; 11
1; c; 1980-10-01; 30
2; a; 1973-10-01; 11
-------- In descending order of userId ------------------
3; B; 1980-12-01; 11
2; a; 1973-10-01; 11
1; c; 1980-10-01; 30
--------- Sort by username -----------------
2; a; 1973-10-01; 11
3; B; 1980-12-01; 11
1; c; 1980-10-01; 30
--------- Sort by birthDate -----------------
2; a; 1973-10-01; 11
1; c; 1980-10-01; 30
3; B; 1980-12-01; 11
Note: The date sorting is first sorted by format conversion, otherwise there will be no correct results.