封装的排序
Posted IT的鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装的排序相关的知识,希望对你有一定的参考价值。
package com.mti.scst.util;
import lombok.Data;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* 动态实体和动态字段 List排序工具
*
* @author huqiao
* @since 2021-08-23
*/
public class ListBeanSortUtil<T>
/**
* api版本
*
* @param list 需要排序的实体集
* @param filed 排序字段
* @param order true 升序 false 降序
*/
public List<T> sort(List<T> list, String filed, boolean order)
if (isEmpty(list, filed))
return new ArrayList<>();
Comparator<?> cmp = ComparableComparator.getInstance();
cmp = order ? ComparatorUtils.nullLowComparator(cmp) : ComparatorUtils.reversedComparator(cmp);
list.sort(new BeanComparator<>(filed, cmp));
return list;
/**
* 算法版
*
* @param list 需要排序的实体集
* @param order true 升序 false 降序
* @param filed 排序字段
*/
public List<T> sort(List<T> list, boolean order, String filed)
if (isEmpty(list, filed))
return new ArrayList<>();
List<T> newList = new ArrayList<>();
for (T t : list)
if (newList.isEmpty())
newList.add(t);
else
for (int i = newList.size() - 1; i >= 0; i--)
if (order ?
(String.valueOf(get(t, filed)).compareTo(String.valueOf(get(newList.get(i), filed))) > 0)
:
(String.valueOf(get(newList.get(i), filed)).compareTo(String.valueOf(get(t, filed))) > 0))
newList.add(i + 1, t);
break;
else if (i == 0)
newList.add(i, t);
return newList;
private boolean isEmpty(List<T> list, String filed)
return list == null || list.isEmpty() || filed == null || filed.isEmpty();
private Object get(T item, String fieldName)
try
return item.getClass().getMethod(String.format("%s%s%s", "get", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1))).invoke(item);
catch (Exception e)
return null;
public static void main(String[] args)
User u1 = new User();
u1.setA("1");
u1.setC("2021-11-07 15:30:10");
User u2 = new User();
u2.setA("3");
u2.setC("2021-11-07 15:30:20");
User u3 = new User();
u3.setA("2");
u3.setC("2021-11-07 15:40:30");
User u4 = new User();
u4.setA("2");
u4.setC("2021-11-08 15:40:30");
User u5 = new User();
u5.setA("1");
u5.setC("2021-11-06 15:40:30");
List<User> list = new ArrayList<>();
list.add(u1);
list.add(u2);
list.add(u3);
list.add(u4);
list.add(u5);
ListBeanSortUtil<User> l = new ListBeanSortUtil<>();
// List<User> result = l.sort(list, false, "c");
// System.out.println(result);
List<User> result2 = l.sort(list, "c", false);
System.out.println(result2);
@Data
static class User
private String a;
private int b;
private String c;
public String getA()
return a;
public void setA(String a)
this.a = a;
public int getB()
return b;
public void setB(int b)
this.b = b;
public String getC()
return c;
public void setC(String c)
this.c = c;
以上是关于封装的排序的主要内容,如果未能解决你的问题,请参考以下文章