java list按照元素对象的指定多个字段属性进行排序

转载 2016年12月27日 11:39:02

见: http://blog.csdn.net/enable1234___/article/details/53224740

ListUtils.Java---功能类

  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

  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---测试

  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. }

运行结果

  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]
 
转载:http://blog.csdn.net/jiangyu1013/article/details/53894218

最新文章

  1. 如何在Mac系统里面更新 Ansible 的 Extra Modules
  2. JavaScript 之 for语句
  3. Unity-Animator深入系列---StateMachineBehaviour状态机脚本学习
  4. log tree(merge)
  5. 【LeetCode】100 - Same Tree
  6. 数学概念——F 概率(经典问题)birthday paradox
  7. Delphi 把一个ICO转换为BMP
  8. Java学习之路:ArrayList用法
  9. Windows API 之 GetModuleHandle
  10. 高性能 AJAX
  11. JavaScript参考
  12. Android开发之漫漫长途 XVI——ListView与RecyclerView项目实战
  13. VS fopen sprinft ... unsafe 问题
  14. Dynamic Rankings ZOJ - 2112(主席树+树状数组)
  15. adb install与pm install 区别
  16. mybtis逆向工程实战教程--条件查询
  17. [转载]在Windows下搭建Android开发环境
  18. Bypass WAF
  19. PS大神的作品,每张都是科幻大片!
  20. java之简单工厂

热门文章

  1. HDU 6656 Kejin Player (期望DP 逆元)
  2. Java反射机制调用私有方法
  3. VMvare+Ubuntu环境安装
  4. 20140806 交换两个数 extern &ldquo;C&rdquo;用法
  5. 1-Navicat无法远程连接Ubuntu上的MySQL(已解决)
  6. python之pypinyin
  7. C语言结构体和函数
  8. .Net中Task使用来提高代码执行效率
  9. H5在js中向指定的元素添加样式
  10. nodejs route的简单使用