当前位置:网站首页>对List进行排序工具类,可以对字符串排序
对List进行排序工具类,可以对字符串排序
2022-07-04 06:00:00 【hello宋先深】
package com.qpyx.common.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
/**
* @Auther: SJH
* @Date: 2022/4/22 10:05
* @Description: list根据对象任意属性排序
*/
public class SortFildOrderUtile {
public static final String DESC = "desc";
public static final String ASC = "asc";
/**
* 对list中的元素按升序排列.
*
* @param list
* 排序集合
* @param field
* 排序字段
* @return
*/
public static List<?> sort(List<?> list, final String field) {
return sort(list, field, null);
}
/**
* 对list中的元素进行排序.
*
* @param list
* 排序集合
* @param field
* 排序字段
* @param sort
* 排序方式: SortListUtil.DESC(降序) SortListUtil.ASC(升序).
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<?> sort(List<?> list, final String field,
final String sort) {
Collections.sort(list, new Comparator() {
@Override
public int compare(Object a, Object b) {
int ret = 0;
try {
Field f = a.getClass().getDeclaredField(field);
f.setAccessible(true);
Class<?> type = f.getType();
if (type == int.class) {
ret = ((Integer) f.getInt(a)).compareTo((Integer) f
.getInt(b));
} else if (type == double.class) {
ret = ((Double) f.getDouble(a)).compareTo((Double) f
.getDouble(b));
} else if (type == long.class) {
ret = ((Long) f.getLong(a)).compareTo((Long) f
.getLong(b));
} else if (type == float.class) {
ret = ((Float) f.getFloat(a)).compareTo((Float) f
.getFloat(b));
} else if (type == Date.class) {
ret = ((Date) f.get(a)).compareTo((Date) f.get(b));
} else if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) f.get(a)).compareTo((Comparable) f
.get(b));
} else {
ret = String.valueOf(f.get(a)).compareTo(
String.valueOf(f.get(b)));
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (sort != null && sort.toLowerCase().equals(DESC)) {
return -ret;
} else {
return ret;
}
}
});
return list;
}
/**
* 对list中的元素按fields和sorts进行排序,
* fields[i]指定排序字段,sorts[i]指定排序方式.如果sorts[i]为空则默认按升序排列.
*
* @param list
* 排序集合
* @param fields
* 排序字段-数组(一个或多个)
* @param sorts
* 排序规则-数组(一个或多个)
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<?> sort(List<?> list, String[] fields, String[] sorts) {
if (fields != null && fields.length > 0) {
for (int i = fields.length - 1; i >= 0; i--) {
final String field = fields[i];
String tmpSort = ASC;
if (sorts != null && sorts.length > i && sorts[i] != null) {
tmpSort = sorts[i];
}
final String sort = tmpSort;
Collections.sort(list, new Comparator() {
@Override
public int compare(Object a, Object b) {
int ret = 0;
try {
Field f = a.getClass().getDeclaredField(field);
f.setAccessible(true);
Class<?> type = f.getType();
if (type == int.class) {
ret = ((Integer) f.getInt(a))
.compareTo((Integer) f.getInt(b));
} else if (type == double.class) {
ret = ((Double) f.getDouble(a))
.compareTo((Double) f.getDouble(b));
} else if (type == long.class) {
ret = ((Long) f.getLong(a)).compareTo((Long) f
.getLong(b));
} else if (type == float.class) {
ret = ((Float) f.getFloat(a))
.compareTo((Float) f.getFloat(b));
} else if (type == Date.class) {
ret = ((Date) f.get(a)).compareTo((Date) f
.get(b));
} else if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) f.get(a))
.compareTo((Comparable) f.get(b));
} else {
ret = String.valueOf(f.get(a)).compareTo(
String.valueOf(f.get(b)));
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (sort != null && sort.toLowerCase().equals(DESC)) {
return -ret;
} else {
return ret;
}
}
});
}
}
return list;
}
/**
* 判断对象实现的所有接口中是否包含szInterface
*
* @param clazz
* @param szInterface
* @return
*/
public static boolean isImplementsOf(Class<?> clazz, Class<?> szInterface) {
boolean flag = false;
Class<?>[] face = clazz.getInterfaces();
for (Class<?> c : face) {
if (c == szInterface) {
flag = true;
} else {
flag = isImplementsOf(c, szInterface);
}
}
if (!flag && null != clazz.getSuperclass()) {
return isImplementsOf(clazz.getSuperclass(), szInterface);
}
return flag;
}
}
边栏推荐
- ES6 模块化
- Risc-v-qemu-virt in FreeRTOS_ Lock mechanism analysis of GCC
- How to get the parent node of all nodes in El tree
- JSON Web Token----JWT和传统session登录认证对比
- BeanFactoryPostProcessor 与 BeanPostProcessor 相关子类概述
- Tutle clock improved version
- Configure cross compilation tool chain and environment variables
- left_ and_ right_ Net normal version
- QT 获取随机颜色值设置label背景色 代码
- Review | categories and mechanisms of action of covid-19 neutralizing antibodies and small molecule drugs
猜你喜欢

Weekly summary (*63): about positive energy
![BUU-Crypto-[GUET-CTF2019]BabyRSA](/img/87/157066155e8d3a93e30a68eaf1781b.jpg)
BUU-Crypto-[GUET-CTF2019]BabyRSA

Introduction to AMBA

JSON Web Token----JWT和傳統session登錄認證對比

如何实现视频平台会员多账号登录

QT qtablewidget table column top requirements ideas and codes
![[microservice] Nacos cluster building and loading file configuration](/img/50/7af220c57a06eb186729c9882d9dab.png)
[microservice] Nacos cluster building and loading file configuration

webrtc 快速搭建 视频通话 视频会议

JS扁平化数形结构的数组

Grounding relay dd-1/60
随机推荐
APScheduler如何设置任务不并发(即第一个任务执行完再执行下一个)?
Accidentally deleted the data file of Clickhouse, can it be restored?
[microservice] Nacos cluster building and loading file configuration
How does apscheduler set tasks not to be concurrent (that is, execute the next task after the first one)?
Use of hutool Pinyin tool
Penetration tool - sqlmap
Overview of relevant subclasses of beanfactorypostprocessor and beanpostprocessor
Webrtc quickly set up video call and video conference
left_and_right_net正常版本
AWT introduction
FRP intranet penetration, reverse proxy
Nexus 6p downgraded from 8.0 to 6.0+root
Practical gadget instructions
js arguments参数使用和详解
What are the reasons for the frequent high CPU of ECS?
冲击继电器JC-7/11/DC110V
JS get the attribute values nested in the object
报错cvc-complex-type.2.4.a: 发现了以元素 ‘base-extension‘ 开头的无效内容。应以 ‘{layoutlib}‘ 之一开头。
Review | categories and mechanisms of action of covid-19 neutralizing antibodies and small molecule drugs
卸载Google Drive 硬盘-必须退出程序才能卸载