1. 程式人生 > >java list按照元素對象的指定多個字段屬性進行排序

java list按照元素對象的指定多個字段屬性進行排序

ase 日期 pri num tex itl pop sha 轉換

ListUtils.Java---功能類

http://blog.csdn.net/jiangyu1013/article/details/53894218

[java] view plain copy
  1. package com.enable.common.utils;
  2. import java.lang.reflect.Field;
  3. import java.text.NumberFormat;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.Date;
  7. import java.util.List;
  8. /**
  9. * @author yinaibang
  10. * 在數據庫中查出來的列表中,往往需要對不同的字段重新排序。 一般的做法都是使用排序的字段,重新到數據庫中查詢。
  11. * 如果不到數據庫查詢,直接在第一次查出來的list中排序,無疑會提高系統的性能。 下面就寫一個通用的方法,對list排序,
  12. *
  13. * 至少需要滿足以下5點:
  14. *
  15. * ①.list元素對象類型任意
  16. * ---->使用泛型解決
  17. *
  18. * ②.可以按照list元素對象的任意多個屬性進行排序,即可以同時指定多個屬性進行排序
  19. * --->使用java的可變參數解決
  20. *
  21. * ③.list元素對象屬性的類型可以是數字(byte、short、int、long、float、double等,包括正數、負數、0)、字符串(char、String)、日期(java.util.Date)
  22. * --->對於數字:統一轉換為固定長度的字符串解決,比如數字3和123,轉換為"003"和"123" ;再比如"-15"和"7"轉換為"-015"和"007"
  23. * --->對於日期:可以先把日期轉化為long類型的數字,數字的解決方法如上
  24. *
  25. * ④.list元素對象的屬性可以沒有相應的getter和setter方法
  26. * --->可以使用java反射進行獲取private和protected修飾的屬性值
  27. *
  28. * ⑤.list元素對象的對象的每個屬性都可以指定是升序還是降序
  29. * -->使用2個重寫的方法(一個方法滿足所有屬性都按照升序(降序),另外一個方法滿足每個屬性都能指定是升序(降序))
  30. *
  31. *
  32. */
  33. public class ListUtils {
  34. /**
  35. * 對list的元素按照多個屬性名稱排序,
  36. * list元素的屬性可以是數字(byte、short、int、long、float、double等,支持正數、負數、0)、char、String、java.util.Date
  37. *
  38. *
  39. * @param lsit
  40. * @param sortname
  41. * list元素的屬性名稱
  42. * @param isAsc
  43. * true升序,false降序
  44. */
  45. public static <E> void sort(List<E> list, final boolean isAsc, final String... sortnameArr) {
  46. Collections.sort(list, new Comparator<E>() {
  47. public int compare(E a, E b) {
  48. int ret = 0;
  49. try {
  50. for (int i = 0; i < sortnameArr.length; i++) {
  51. ret = ListUtils.compareObject(sortnameArr[i], isAsc, a, b);
  52. if (0 != ret) {
  53. break;
  54. }
  55. }
  56. } catch (Exception e) {
  57. e.printStackTrace();
  58. }
  59. return ret;
  60. }
  61. });
  62. }
  63. /**
  64. * 給list的每個屬性都指定是升序還是降序
  65. *
  66. * @param list
  67. * @param sortnameArr 參數數組
  68. * @param typeArr 每個屬性對應的升降序數組, true升序,false降序
  69. */
  70. public static <E> void sort(List<E> list, final String[] sortnameArr, final boolean[] typeArr) {
  71. if (sortnameArr.length != typeArr.length) {
  72. throw new RuntimeException("屬性數組元素個數和升降序數組元素個數不相等");
  73. }
  74. Collections.sort(list, new Comparator<E>() {
  75. public int compare(E a, E b) {
  76. int ret = 0;
  77. try {
  78. for (int i = 0; i < sortnameArr.length; i++) {
  79. ret = ListUtils.compareObject(sortnameArr[i], typeArr[i], a, b);
  80. if (0 != ret) {
  81. break;
  82. }
  83. }
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. return ret;
  88. }
  89. });
  90. }
  91. /**
  92. * 對2個對象按照指定屬性名稱進行排序
  93. *
  94. * @param sortname
  95. * 屬性名稱
  96. * @param isAsc
  97. * true升序,false降序
  98. * @param a
  99. * @param b
  100. * @return
  101. * @throws Exception
  102. */
  103. private static <E> int compareObject(final String sortname, final boolean isAsc, E a, E b) throws Exception {
  104. int ret;
  105. Object value1 = ListUtils.forceGetFieldValue(a, sortname);
  106. Object value2 = ListUtils.forceGetFieldValue(b, sortname);
  107. String str1 = value1.toString();
  108. String str2 = value2.toString();
  109. if (value1 instanceof Number && value2 instanceof Number) {
  110. int maxlen = Math.max(str1.length(), str2.length());
  111. str1 = ListUtils.addZero2Str((Number) value1, maxlen);
  112. str2 = ListUtils.addZero2Str((Number) value2, maxlen);
  113. } else if (value1 instanceof Date && value2 instanceof Date) {
  114. long time1 = ((Date) value1).getTime();
  115. long time2 = ((Date) value2).getTime();
  116. int maxlen = Long.toString(Math.max(time1, time2)).length();
  117. str1 = ListUtils.addZero2Str(time1, maxlen);
  118. str2 = ListUtils.addZero2Str(time2, maxlen);
  119. }
  120. if (isAsc) {
  121. ret = str1.compareTo(str2);
  122. } else {
  123. ret = str2.compareTo(str1);
  124. }
  125. return ret;
  126. }
  127. /**
  128. * 給數字對象按照指定長度在左側補0.
  129. *
  130. * 使用案例: addZero2Str(11,4) 返回 "0011", addZero2Str(-18,6)返回 "-000018"
  131. *
  132. * @param numObj
  133. * 數字對象
  134. * @param length
  135. * 指定的長度
  136. * @return
  137. */
  138. public static String addZero2Str(Number numObj, int length) {
  139. NumberFormat nf = NumberFormat.getInstance();
  140. // 設置是否使用分組
  141. nf.setGroupingUsed(false);
  142. // 設置最大整數位數
  143. nf.setMaximumIntegerDigits(length);
  144. // 設置最小整數位數
  145. nf.setMinimumIntegerDigits(length);
  146. return nf.format(numObj);
  147. }
  148. /**
  149. * 獲取指定對象的指定屬性值(去除private,protected的限制)
  150. *
  151. * @param obj
  152. * 屬性名稱所在的對象
  153. * @param fieldName
  154. * 屬性名稱
  155. * @return
  156. * @throws Exception
  157. */
  158. public static Object forceGetFieldValue(Object obj, String fieldName) throws Exception {
  159. Field field = obj.getClass().getDeclaredField(fieldName);
  160. Object object = null;
  161. boolean accessible = field.isAccessible();
  162. if (!accessible) {
  163. // 如果是private,protected修飾的屬性,需要修改為可以訪問的
  164. field.setAccessible(true);
  165. object = field.get(obj);
  166. // 還原private,protected屬性的訪問性質
  167. field.setAccessible(accessible);
  168. return object;
  169. }
  170. object = field.get(obj);
  171. return object;
  172. }
  173. }

UserInfo.java

[java] view plain copy
  1. package com;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. /**
  5. *
  6. * @author yinaibang
  7. *
  8. */
  9. public class UserInfo implements java.io.Serializable {
  10. private static final long serialVersionUID = -3522051445403971732L;
  11. private Integer userId;
  12. private String username;
  13. private Date birthDate;
  14. private Integer age;
  15. private float fRate;
  16. private char ch;
  17. public Date getBirthDate() {
  18. return birthDate;
  19. }
  20. public String getBirthDatestr() {
  21. SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
  22. return formater.format(getBirthDate());
  23. }
  24. public UserInfo(Integer userId, String username, Date birthDate, Integer age, float fRate, char ch) {
  25. super();
  26. this.userId = userId;
  27. this.username = username;
  28. this.birthDate = birthDate;
  29. this.age = age;
  30. this.fRate = fRate;
  31. this.ch = ch;
  32. }
  33. @Override
  34. public String toString() {
  35. return "UserInfo [userId=" + userId + ", \tusername=" + username + ", \tbirthDate=" + getBirthDatestr()
  36. + ", \tage=" + age + ", fRate=" + fRate + ", ch=" + ch + "]";
  37. }
  38. }


Test.java---測試類

[java] view plain copy
  1. package com;
  2. import java.text.SimpleDateFormat;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import com.enable.common.utils.ListUtils;
  6. /**
  7. *
  8. * @author yinaibang
  9. *
  10. */
  11. public class Test {
  12. public static void main(String[] args) throws Exception {
  13. Test testObj = new Test();
  14. List<UserInfo> list = new ArrayList<UserInfo>();
  15. // public UserInfo(Integer userId, String username, Date birthDate,Integer age, float fRate, char ch)
  16. SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
  17. UserInfo user1 = new UserInfo(3, "bbb", formater.parse("1980-12-01"), 1, 1.2f, ‘a‘);
  18. UserInfo user2 = new UserInfo(0, "126", formater.parse("1900-10-11"), 03, -3.6f, ‘c‘);
  19. UserInfo user3 = new UserInfo(12, "5", formater.parse("1973-08-21"), 15, 9.32f, ‘f‘);
  20. UserInfo user4 = new UserInfo(465, "1567", formater.parse("2012-01-26"), 20, 12.56f, ‘0‘);
  21. UserInfo user5 = new UserInfo(2006, "&4m", formater.parse("2010-05-08"), 100, 165.32f, ‘5‘);
  22. UserInfo user6 = new UserInfo(5487, "hf67", formater.parse("2016-12-30"), 103, 56.32f, ‘m‘);
  23. UserInfo user7 = new UserInfo(5487,"jigg", formater.parse("2000-10-16"), 103, 56.32f, ‘m‘);
  24. UserInfo user8 = new UserInfo(5487, "jigg", formater.parse("1987-07-25"), 103, 56.32f, ‘m‘);
  25. list.add(user1);
  26. list.add(user2);
  27. list.add(user3);
  28. list.add(user4);
  29. list.add(user5);
  30. list.add(user6);
  31. list.add(user7);
  32. list.add(user8);
  33. System.out.println("\n-------原來序列-------------------");
  34. testObj.printfUserInfoList(list);
  35. // 按userId升序、username降序、birthDate升序排序
  36. String [] sortNameArr = {"userId","username","birthDate"};
  37. boolean [] isAscArr = {true,false,true};
  38. ListUtils.sort(list,sortNameArr,isAscArr);
  39. System.out.println("\n--------按按userId升序、username降序、birthDate升序排序(如果userId相同,則按照username降序,如果username相同,則按照birthDate升序)------------------");
  40. testObj.printfUserInfoList(list);
  41. // 按userId、username、birthDate都升序排序
  42. ListUtils.sort(list, true, "userId", "username","birthDate");
  43. System.out.println("\n--------按userId、username、birthDate排序(如果userId相同,則按照username升序,如果username相同,則按照birthDate升序)------------------");
  44. testObj.printfUserInfoList(list);
  45. // 按userId、username都倒序排序
  46. ListUtils.sort(list, false, "userId", "username");
  47. System.out.println("\n--------按userId和username倒序(如果userId相同,則按照username倒序)------------------");
  48. testObj.printfUserInfoList(list);
  49. // 按username、birthDate都升序排序
  50. ListUtils.sort(list, true, "username", "birthDate");
  51. System.out.println("\n---------按username、birthDate升序(如果username相同,則按照birthDate升序)-----------------");
  52. testObj.printfUserInfoList(list);
  53. // 按birthDate倒序排序
  54. ListUtils.sort(list, false, "birthDate");
  55. System.out.println("\n---------按birthDate倒序-----------------");
  56. testObj.printfUserInfoList(list);
  57. // 按fRate升序排序
  58. ListUtils.sort(list, true, "fRate");
  59. System.out.println("\n---------按fRate升序-----------------");
  60. testObj.printfUserInfoList(list);
  61. // 按ch倒序排序
  62. ListUtils.sort(list, false, "ch");
  63. System.out.println("\n---------按ch倒序-----------------");
  64. testObj.printfUserInfoList(list);
  65. }
  66. private void printfUserInfoList(List<UserInfo> list) {
  67. for (UserInfo user : list) {
  68. System.out.println(user.toString());
  69. }
  70. }
  71. }

運行結果

[java] view plain copy
  1. -------原來序列-------------------
  2. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  3. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  4. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  5. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
  6. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  7. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  8. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  9. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  10. --------按按userId升序、username降序、birthDate升序排序(如果userId相同,則按照username降序,如果username相同,則按照birthDate升序)------------------
  11. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  12. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  13. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  14. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
  15. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  16. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  17. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  18. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  19. --------按userId、username、birthDate排序(如果userId相同,則按照username升序,如果username相同,則按照birthDate升序)------------------
  20. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  21. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  22. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  23. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
  24. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  25. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  26. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  27. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  28. --------按userId和username倒序(如果userId相同,則按照username倒序)------------------
  29. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  30. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  31. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  32. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  33. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
  34. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  35. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  36. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  37. ---------按username、birthDate升序(如果username相同,則按照birthDate升序)-----------------
  38. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  39. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  40. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
  41. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  42. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  43. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  44. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  45. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  46. ---------按birthDate倒序-----------------
  47. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  48. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
  49. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  50. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  51. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  52. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  53. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  54. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  55. ---------按fRate升序-----------------
  56. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  57. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  58. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  59. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
  60. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  61. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  62. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  63. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  64. ---------按ch倒序-----------------
  65. UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
  66. UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
  67. UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
  68. UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
  69. UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
  70. UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
  71. UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
  72. UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
技術分享
1
0

java list按照元素對象的指定多個字段屬性進行排序