List自定义对象的排序,根据对象的某一列进行排序

Stella981
• 阅读 563

   在工作中,经常需要对List对象集合进行排序操作,下面总结下搞个通用排序对象,原理是使用JAVA的  

   Comparator    接口实现排序   不多说直接上“干货”

1、存在实体类:

 1     @Data
 2     @AllArgsConstructor
 3     @NoArgsConstructor
 4     class Book {
 5         private Long id;//编号
 6         private String userName;//书本名称
 7         private double productPrice;//书本价格
 8         private String author;//作者
 9         private Integer weight;//权重
10     }

2、SortList  排序实现通用类:

 1 @Data
 2 @AllArgsConstructor
 3 @NoArgsConstructor
 4 public class SortList<T> implements Comparator<T> {
 5 
 6     //需要比较的对象属性字段名称
 7     private String  propertyName;
 8     //是否是升序排序
 9     private boolean isAsc;
10 
11     /**
12      * 需要的是:根据类中的字段对对象进行排序
13      *
14      * @return
15      */
16 
17     @Override
18     public int compare(T b1, T b2) {
19 
20         Class<?> clz = b1.getClass();
21         Method method = getPropertyMethod(clz, propertyName);
22         try {
23 
24             Object objectOne = method.invoke(b1);
25 
26             Object objectTwo = method.invoke(b2);
27 
28             if (objectOne == null || objectTwo == null) {
29                 return 0;
30             }
31 
32             Comparable value1 = (Comparable) objectOne;
33 
34             Comparable value2 = (Comparable) objectTwo;
35 
36             if (isAsc) {
37                 return value1.compareTo(value2);
38             } else {
39                 return value2.compareTo(value1);
40             }
41         } catch (Exception e) {
42             e.printStackTrace();
43         }
44         return 0;
45     }
46 
47     // 获取类名
48     public static Method getPropertyMethod(Class clz, String propertyName) {
49         Method method = null;
50         try {
51             method = clz.getMethod("get" + firstUpperCase(propertyName));
52         } catch (Exception e) {
53             System.out.println("获取类名发生错误!");
54         }
55         return method;
56     }
57 
58     /**
59      * 首字母大写方法
60      * @param str
61      * @return
62      */
63     public static String firstUpperCase(String str) {
64         char[] ch = str.toCharArray();
65         if (ch[0] >= 'a' && ch[0] <= 'z') {
66             ch[0] = (char) (ch[0] - 32);
67         }
68         return new String(ch);
69     }
70 
71 }

3、实际使用测试如下:  主要这么来使用   

Collections.sort(bookList, new SortList<Book>("productPrice",true));

测试

 1 @Test
 2     public void sortBook() {
 3         List<Book> bookList = getBookList();
 4         System.out.println("原先的顺序:");
 5         printf(bookList);
 6 
 7         System.out.println("根据价格排序:");
 8         Collections.sort(bookList, new SortList<Book>("productPrice",true));
 9         printf(bookList);
10 
11         System.out.println("根据Id排序:");
12         Collections.sort(bookList, new SortList<Book>("id",false));
13         printf(bookList);
14 
15         System.out.println("根据weight排序:");
16         Collections.sort(bookList, new SortList<Book>("weight",true));
17         printf(bookList);
18 
19         System.out.println("根据userName排序:");
20         Collections.sort(bookList, new SortList<Book>("userName",true));
21         printf(bookList);
22 
23 
24     }
25 
26     public List<Book> getBookList() {
27         List<Book> books = Lists.newArrayList();
28         Book book1 = new Book(1L, "first", 10.00, "zhangsan", 19);
29         Book book2 = new Book(2L, "wirst", 9.00, "zhangsan", 24);
30         Book book3 = new Book(3L, "eirst", 8.00, "zhangsan", 29);
31         Book book4 = new Book(4L, "girst", 7.00, "zhangsan", 13);
32         Book book5 = new Book(5L, "tirst", 6.00, "zhangsan", 14);
33 
34         books.add(book1);
35         books.add(book2);
36         books.add(book3);
37         books.add(book4);
38         books.add(book5);
39 
40         return books;
41     }
42 
43     /**
44      * 打印函数
45      *
46      * @param lisbk
47      */
48     public void printf(List<Book> lisbk) {
49         if (lisbk.isEmpty() || lisbk == null) {
50             System.out.println("没有数据");
51             return;
52         }
53         for (Book book : lisbk) {
54             System.out.println("Id: " + book.getId() + "   userName: " + book.getUserName() + "   price: " + book.getProductPrice() + "  weight:" + book.getWeight());
55         }
56         System.out.println();
57         return;
58     }

执行结果如下:

List自定义对象的排序,根据对象的某一列进行排序

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
执键写春秋 执键写春秋
2年前
Java中集合排序常用的方式
1.集合排序概述1.1集合排序的主要内容:集合中的级别数据类型排序集合中的字符串排序Comparator接口Comparable接口1.2数组排序回顾intarr12,25,22,17,89,22;Arrays.sort(arr);输出:12,17,22,22,25,89Java的Arrays类中有一个sort()方法,该方法是Ar
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
java 数据结构(十二):Collections工具类的使用
Collections工具类1.作用:操作Collection和Map的工具类2.常用方法:reverse(List):反转List中元素的顺序shuffle(List):对List集合元素进行随机排序sort(List):根据元素的自然顺序对指定List集合元素升序排序sort(List,Comparator)
Wesley13 Wesley13
2年前
java8新特性
Stream将List转换为Map,使用Collectors.toMap方法进行转换背景:User类,类中分别有id,name,age三个属性。List集合,userList,存储User对象1、指定keyvalue,value是对象中的某个属性值。 Map<Integer,StringuserMap1userList.str
Wesley13 Wesley13
2年前
java反射练习 对集合中元素 按照方法进行排序
/\\\对集合中元素按照指定方法进行排序\\@paramlist需要排序的集合\@paramproperty时间对象在集合对象中属性名称\@parammethod排序字段get方法\@paramreverse是否倒序\/publicstatic<Tvoidsor
Wesley13 Wesley13
2年前
java.lang.Comparable
Comparable接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的_自然排序_,类的compareTo方法被称为它的_自然比较方法_。实现此接口的对象列表(和数组)可以通过Collections.sort(和Arrays.sort)进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器。
Wesley13 Wesley13
2年前
Java比较器
前言本篇文章主要介绍的是Java比较器的实现与测试。1.java.lang.Comparable排序接口定义:Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays
Stella981 Stella981
2年前
JS 对象数组Array 根据对象object key的值排序sort,很风骚哦
有个js对象数组varary\{id:1,name:"b"},{id:2,name:"b"}\需求是根据name或者id的值来排序,这里有个风骚的函数函数定义:function keysrt(key,desc) {  return function(a,b){    return desc ? ~~(ak
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable