list集合排序3
java list按照元素对象的指定多个字段属性进行排序
见: http://blog.csdn.net/enable1234___/article/details/53224740
ListUtils.Java---功能类
- 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
- * 在数据库中查出来的列表中,往往需要对不同的字段重新排序。 一般的做法都是使用排序的字段,重新到数据库中查询。
- * 如果不到数据库查询,直接在第一次查出来的list中排序,无疑会提高系统的性能。 下面就写一个通用的方法,对list排序,
- *
- * 至少需要满足以下5点:
- *
- * ①.list元素对象类型任意
- * ---->使用泛型解决
- *
- * ②.可以按照list元素对象的任意多个属性进行排序,即可以同时指定多个属性进行排序
- * --->使用java的可变参数解决
- *
- * ③.list元素对象属性的类型可以是数字(byte、short、int、long、float、double等,包括正数、负数、0)、字符串(char、String)、日期(java.util.Date)
- * --->对于数字:统一转换为固定长度的字符串解决,比如数字3和123,转换为"003"和"123" ;再比如"-15"和"7"转换为"-015"和"007"
- * --->对于日期:可以先把日期转化为long类型的数字,数字的解决方法如上
- *
- * ④.list元素对象的属性可以没有相应的getter和setter方法
- * --->可以使用java反射进行获取private和protected修饰的属性值
- *
- * ⑤.list元素对象的对象的每个属性都可以指定是升序还是降序
- * -->使用2个重写的方法(一个方法满足所有属性都按照升序(降序),另外一个方法满足每个属性都能指定是升序(降序))
- *
- *
- */
- public class ListUtils {
- /**
- * 对list的元素按照多个属性名称排序,
- * list元素的属性可以是数字(byte、short、int、long、float、double等,支持正数、负数、0)、char、String、java.util.Date
- *
- *
- * @param lsit
- * @param sortname
- * list元素的属性名称
- * @param isAsc
- * true升序,false降序
- */
- 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;
- }
- });
- }
- /**
- * 给list的每个属性都指定是升序还是降序
- *
- * @param list
- * @param sortnameArr 参数数组
- * @param typeArr 每个属性对应的升降序数组, true升序,false降序
- */
- public static <E> void sort(List<E> list, final String[] sortnameArr, final boolean[] typeArr) {
- if (sortnameArr.length != typeArr.length) {
- throw new RuntimeException("属性数组元素个数和升降序数组元素个数不相等");
- }
- 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;
- }
- });
- }
- /**
- * 对2个对象按照指定属性名称进行排序
- *
- * @param sortname
- * 属性名称
- * @param isAsc
- * true升序,false降序
- * @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;
- }
- /**
- * 给数字对象按照指定长度在左侧补0.
- *
- * 使用案例: addZero2Str(11,4) 返回 "0011", addZero2Str(-18,6)返回 "-000018"
- *
- * @param numObj
- * 数字对象
- * @param length
- * 指定的长度
- * @return
- */
- public static String addZero2Str(Number numObj, int length) {
- NumberFormat nf = NumberFormat.getInstance();
- // 设置是否使用分组
- nf.setGroupingUsed(false);
- // 设置最大整数位数
- nf.setMaximumIntegerDigits(length);
- // 设置最小整数位数
- nf.setMinimumIntegerDigits(length);
- return nf.format(numObj);
- }
- /**
- * 获取指定对象的指定属性值(去除private,protected的限制)
- *
- * @param obj
- * 属性名称所在的对象
- * @param fieldName
- * 属性名称
- * @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) {
- // 如果是private,protected修饰的属性,需要修改为可以访问的
- field.setAccessible(true);
- object = field.get(obj);
- // 还原private,protected属性的访问性质
- 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.java---测试类
- 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 age, 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"), 03, -3.6f, 'c');
- UserInfo user3 = new UserInfo(12, "5", formater.parse("1973-08-21"), 15, 9.32f, 'f');
- UserInfo user4 = new UserInfo(465, "1567", formater.parse("2012-01-26"), 20, 12.56f, '0');
- UserInfo user5 = new UserInfo(2006, "&4m", formater.parse("2010-05-08"), 100, 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-------原来序列-------------------");
- testObj.printfUserInfoList(list);
- // 按userId升序、username降序、birthDate升序排序
- String [] sortNameArr = {"userId","username","birthDate"};
- boolean [] isAscArr = {true,false,true};
- ListUtils.sort(list,sortNameArr,isAscArr);
- System.out.println("\n--------按按userId升序、username降序、birthDate升序排序(如果userId相同,则按照username降序,如果username相同,则按照birthDate升序)------------------");
- testObj.printfUserInfoList(list);
- // 按userId、username、birthDate都升序排序
- ListUtils.sort(list, true, "userId", "username","birthDate");
- System.out.println("\n--------按userId、username、birthDate排序(如果userId相同,则按照username升序,如果username相同,则按照birthDate升序)------------------");
- testObj.printfUserInfoList(list);
- // 按userId、username都倒序排序
- ListUtils.sort(list, false, "userId", "username");
- System.out.println("\n--------按userId和username倒序(如果userId相同,则按照username倒序)------------------");
- testObj.printfUserInfoList(list);
- // 按username、birthDate都升序排序
- ListUtils.sort(list, true, "username", "birthDate");
- System.out.println("\n---------按username、birthDate升序(如果username相同,则按照birthDate升序)-----------------");
- testObj.printfUserInfoList(list);
- // 按birthDate倒序排序
- ListUtils.sort(list, false, "birthDate");
- System.out.println("\n---------按birthDate倒序-----------------");
- testObj.printfUserInfoList(list);
- // 按fRate升序排序
- ListUtils.sort(list, true, "fRate");
- System.out.println("\n---------按fRate升序-----------------");
- testObj.printfUserInfoList(list);
- // 按ch倒序排序
- ListUtils.sort(list, false, "ch");
- System.out.println("\n---------按ch倒序-----------------");
- testObj.printfUserInfoList(list);
- }
- private void printfUserInfoList(List<UserInfo> list) {
- for (UserInfo user : list) {
- System.out.println(user.toString());
- }
- }
- }
运行结果
- -------原来序列-------------------
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- --------按按userId升序、username降序、birthDate升序排序(如果userId相同,则按照username降序,如果username相同,则按照birthDate升序)------------------
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- --------按userId、username、birthDate排序(如果userId相同,则按照username升序,如果username相同,则按照birthDate升序)------------------
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- --------按userId和username倒序(如果userId相同,则按照username倒序)------------------
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- ---------按username、birthDate升序(如果username相同,则按照birthDate升序)-----------------
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- ---------按birthDate倒序-----------------
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- ---------按fRate升序-----------------
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- ---------按ch倒序-----------------
- UserInfo [userId=5487, username=hf67, birthDate=2016-12-30, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=2000-10-16, age=103, fRate=56.32, ch=m]
- UserInfo [userId=5487, username=jigg, birthDate=1987-07-25, age=103, fRate=56.32, ch=m]
- UserInfo [userId=12, username=5, birthDate=1973-08-21, age=15, fRate=9.32, ch=f]
- UserInfo [userId=0, username=126, birthDate=1900-10-11, age=3, fRate=-3.6, ch=c]
- UserInfo [userId=3, username=bbb, birthDate=1980-12-01, age=1, fRate=1.2, ch=a]
- UserInfo [userId=2006, username=&4m, birthDate=2010-05-08, age=100, fRate=165.32, ch=5]
- UserInfo [userId=465, username=1567, birthDate=2012-01-26, age=20, fRate=12.56, ch=0]
list集合排序3的更多相关文章
- Java比较器对数组,集合排序一
数组排序非常简单,有前辈们的各种排序算法,再加上Java中强大的数组辅助类Arrays与集合辅助类Collections,使得排序变得非常简单,如果说结合比较器Comparator接口和Collato ...
- ArrayList集合排序
using System;using System.Collections;using System.Collections.Generic;using System.Text; namespace ...
- 【Java进阶】---map集合排序
map集合排序 这篇文章讲的不仅仅是map排序,比如把对象按某一属性排序,它都可以解决这些问题. 比如,有N个对象,每个对象有个属性就是成绩,成绩分:优秀,良好,合格.那我们如何按 ...
- CopyOnWriteArrayList集合排序异常问题
1.集合自定义排序实现 对List集合的自定义排序想必大家都知道要使用如下的方式,通过实现Comparator接口并实现compare方法来实现. /** * * @方法名 changeChain * ...
- 二维码扫描&集合排序
一.二维码扫描机制 二维条码/二维码(2-dimensional bar code)是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的:在代码编制上巧妙地利用构 ...
- .Net中集合排序的一种高级玩法
背景: 学生有名称.学号, 班级有班级名称.班级序号 学校有学校名称.学校编号(序号) 需求 现在需要对学生进行排序 第一排序逻辑 按学校编号(序号)排列 再按班级序号排列 再按学生学号排列 当然,在 ...
- Java集合排序及java集合类详解--(Collection, List, Set, Map)
1 集合框架 1.1 集合框架概述 1.1.1 容器简介 到目前为止,我们已经学习了如何创建多个不同的对象,定义了这些对象以后,我们就可以利用它们来做一 ...
- Java提高(5)---map集合排序
map集合排序 这篇文章讲的不仅仅是map排序,比如把对象按某一属性排序,它都可以解决这些问题. 比如,有N个对象,每个对象有个属性就是成绩,成绩分:优秀,良好,合格.那我们如何按照成绩的好坏进行排序 ...
- 集合排序 Comparator和Comparable的使用区别
Java 排序 Compare Comparator接口 Comparable接口 区别 在Java中使用集合来存储数据时非常常见的,集合排序功能也是常用功能之一.下面看一下如何进行集合排序,常用的 ...
- map集合排序
默认情况下,HashMap.HashTable.TreeMap.LinkedHashMap的排列顺序比较: package com.per.sdg.demo; import java.util.Has ...
随机推荐
- PAT_A1124#Raffle for Weibo Followers
Source: PAT A1124 Raffle for Weibo Followers (20 分) Description: John got a full mark on PAT. He was ...
- node express 会话管理中间件 --- cookie-parser
本文转载自:https://www.cnblogs.com/bq-med/p/8995100.html cookie是由服务器发送给客户端(浏览器)的小量信息. 我们知道,平时上网时都是使用无状态的H ...
- 剑指offer——42最小的K个数
题目描述 输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,. 题解: 原以为书中会有好方法,想不到还是排序和STL这两种方法 ...
- AWT Button类
按钮是一个控制组件,按下时有一个标签,并生成一个事件.当按钮被按下和释放,AWT发送ActionEvent的一个实例的按钮,通过调用按钮上的processEvent.按钮的processEvent方法 ...
- 防止DDOS攻击有效方法:隐藏服务器真实IP
如今,网站服务器的安全受到越来越多的重视,但是难免会遇到黑客使用DDoS攻击网站,为了网站的安全通常都会做好防御,其中防止DDoS攻击有效方法:隐藏服务器真实IP ,该技术能够有效地保护网站的安全. ...
- HTML5和CSS3工具资源汇总
HTML5 & CSS3 准备就绪 该网站通过扇形图表的形式展现了从08年到10年以来各大浏览器对HTML5和CSS3的支持情况.发展势头还是很可观的. HTML5安全手册 CSS3按钮生成器 ...
- windows7远程连接服务器出现身份验证错误,又找不到加密Oracle修正
把以下内容复制到文本中, Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Cur ...
- webapi JWT 认证
第一步 使用ng安装JWT组件 第二步 编写登录和生成token代码 byte[] key = Encoding.UTF8.GetBytes("123456789aaaaaaa") ...
- K-mean matlab 实现代码
一.K均值聚类算法 算法步骤如下: 1.初始化 已知数据集合X,及事先指定聚类的总类数N,在X中随机选取N个对象作为初始的聚类中心. 2.设定迭代终止条件 通常设置最大循环次数或者聚类中心的变化误差. ...
- R语言 数据类型
R语言数据类型 通常,在使用任何编程语言进行编程时,您需要使用各种变量来存储各种信息. 变量只是保留值的存储位置. 这意味着,当你创建一个变量,你必须在内存中保留一些空间来存储它们. 您可能想存储各种 ...