list集合按元素的某一属性排序

(1)在元素的model定义的时候实现Comparable接口,重写compareTo方法,实现需要的比较方式。

关键代码:

完整代码

package com.songyan.demo.collection.list.sort;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @author songyan
 * @date 2020年5月21日 下午4:28:28
 * @desc 学生类(在定义model类的时候定义比较规则)
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student implements Comparable<Student> {
    Integer age;
    Integer score;
    String name;

    /**
     * 重写比较方法(自定义比较规则)
     */
    @Override
    public int compareTo(Student o) {
        return -this.getAge().compareTo(o.getAge());
    }
}
View Code

(2)在比较的时候指定比较的方式

关键代码:

完整代码:

package com.songyan.demo.collection.list.sort;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author songyan
 * @date 2020年5月21日 下午4:31:40
 * @desc 在比较的时候定义比较规则
 */
public class Sort2 {

    public static void sort(List<Student> studentList) {
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return -o1.getScore().compareTo(o2.getScore());
            }
        });
    }
}
View Code

(3)基于反射可以对列表使用元素的任意属性排序

关键代码:

完整代码:

package com.songyan.demo.collection.list.sort;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author songyan
 * @date 2020年5月21日 下午4:33:10
 * @desc 基于反射实现对一个列表的任意字段的排序
 */
public class Sort3 {

    /**
     * 对"指定的集合"根据"指定的字段"排序
     * 
     * @param list
     * @param field
     */
    public static <T> void sort(List<T> list, String field) {
        if (list == null || list.size() == 0) {
            return;
        } else {
            final String fieldName = getFieldName(field);
            Collections.sort(list, new Comparator<T>() {
                @Override
                public int compare(T o1, T o2) {
                    try {
                        Object val1 = getFieldValue(o1, fieldName);
                        Object val2 = getFieldValue(o2, fieldName);
                        
                        if (val1 == null) {
                            if (val2 == null) {
                                return 0;
                            } else {
                                return -1;
                            }
                        }
                        
                        if (val2 == null)
                            return -1;
                        if (val1 instanceof BigDecimal && val2 instanceof BigDecimal) {
                            return -((BigDecimal) val1).compareTo((BigDecimal) val2);
                        } else if (val1 instanceof Integer && val2 instanceof Integer) {
                            return -((Integer) val1).compareTo((Integer) val2);
                        } else if (val1 instanceof String && val2 instanceof String) {
                            return -((String) val1).compareTo((String) val2);
                        } else if (val1 instanceof Date && val2 instanceof Date) {
                            return -((Date) val1).compareTo((Date) val2);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return 1;
                }
            });
        }
    }

    /**
     * 将字段名首字母大写
     * 
     * @param field
     * @return
     */
    private static String getFieldName(String field) {
        if (field != null && field.length() > 0) {
            if (field.length() == 1) {
                field = field.substring(0, 1).toUpperCase();
            } else {
                field = field.substring(0, 1).toUpperCase() + field.substring(1);
            }
        }
        return field;
    }

    /**
     * 获取属性值
     * 
     * @param <T>
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    private static <T> Object getFieldValue(T o1, String field) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Method getter1 = o1.getClass().getDeclaredMethod("get" + field);
        return getter1.invoke(o1);
    }
}
View Code

(4)三种方式的使用:

关键代码:

 

完整代码:

package com.songyan.demo.collection.list.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author songyan
 * @date 2020年5月21日 下午3:17:36
 * @desc list根据某个字段排序
 */
public class ListSortTest {
    public static void main(String[] args) {
        List<Student> studentList = getTestData();

        System.out.println("原始数据");
        printList(studentList);
        
        //第一种排序方式
        System.out.println("按照age排序");
        Collections.sort(studentList);
        printList(studentList);
        
        //第二种排序方式
        System.out.println("按照成绩排序");
        Sort2.sort(studentList);
        printList(studentList);
        
        //第三种排序方式
        System.out.println("按照成绩排序");
        Sort3.sort(studentList,"score");
        printList(studentList);

    }

    /**
     * 获取测试列表数据
     * @return
     */
    private static List<Student> getTestData() {
        Student studnet1 = new Student(1, 50,"name1");
        Student studnet2 = new Student(8, 100,"name6");
        Student studnet3 = new Student(5, 80,"name4");
        Student studnet4 = new Student(3, 99,"name5");
        Student studnet5 = new Student(4, 66,"name8");

        List<Student> studentList = new ArrayList<>();
        studentList.add(studnet1);
        studentList.add(studnet2);
        studentList.add(studnet3);
        studentList.add(studnet4);
        studentList.add(studnet5);
        
        return studentList;
    }

    /**
     * 打印列表数据
     * @param studentList
     */
    public static void printList(List<Student> studentList) {
        if (studentList != null) {
            for (Student student : studentList) {
                System.out.println(student);
            }
        }
        System.out.println();
    }
    
}
View Code

运行结果:

 

 

原文地址:https://www.cnblogs.com/excellencesy/p/12931886.html