当前位置:网站首页>Sort list tool class, which can sort strings
Sort list tool class, which can sort strings
2022-07-04 06:05:00 【Hello song Xianshen】
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 Sort by any attribute of the object
*/
public class SortFildOrderUtile {
public static final String DESC = "desc";
public static final String ASC = "asc";
/**
* Yes list The elements in are arranged in ascending order .
*
* @param list
* Sort set
* @param field
* Sort field
* @return
*/
public static List<?> sort(List<?> list, final String field) {
return sort(list, field, null);
}
/**
* Yes list The elements in are sorted .
*
* @param list
* Sort set
* @param field
* Sort field
* @param sort
* sort order : SortListUtil.DESC( Descending ) SortListUtil.ASC( Ascending ).
* @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;
}
/**
* Yes list The elements in press fields and sorts Sort ,
* fields[i] Specify sort fields ,sorts[i] Specify sort method . If sorts[i] If it is blank, it will be arranged in ascending order by default .
*
* @param list
* Sort set
* @param fields
* Sort field - Array ( One or more )
* @param sorts
* Sort rule - Array ( One or more )
* @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;
}
/**
* Judge whether all interfaces implemented by the object contain 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;
}
}
边栏推荐
- Halcon图片标定,使得后续图片处理过后变成与模板图片一样
- left_ and_ right_ Net normal version
- Arc135 C (the proof is not very clear)
- Invalid bound statement (not found): com. example. mapper. TblUserRecordMapper. login
- 746. Climb stairs with minimum cost
- js如何将秒转换成时分秒显示
- 如何判断数组中是否含有某个元素
- ES6 modularization
- 如何展开Collapse 的所有折叠面板
- js获取对象中嵌套的属性值
猜你喜欢

Uninstall Google drive hard drive - you must exit the program to uninstall

QT 获取随机颜色值设置label背景色 代码

JS扁平化数形结构的数组

Compound nonlinear feedback control (2)

分布式CAP理论
![70000 words of detailed explanation of the whole process of pad openvino [CPU] - from environment configuration to model deployment](/img/3f/36a67544deceb3d3789b500efde89c.jpg)
70000 words of detailed explanation of the whole process of pad openvino [CPU] - from environment configuration to model deployment

Error CVC complex type 2.4. a: Invalid content beginning with element 'base extension' was found. Should start with one of '{layoutlib}'.

Kubernets first meeting

卸载Google Drive 硬盘-必须退出程序才能卸载

input显示当前选择的图片
随机推荐
APScheduler如何设置任务不并发(即第一个任务执行完再执行下一个)?
Functions in C language (detailed explanation)
Webrtc quickly set up video call and video conference
Error CVC complex type 2.4. a: Invalid content beginning with element 'base extension' was found. Should start with one of '{layoutlib}'.
JSON web token -- comparison between JWT and traditional session login authentication
ABAP:OOALV实现增删改查功能
How to determine whether an array contains an element
QT 获取随机颜色值设置label背景色 代码
【无标题】
Json Web token - jwt vs. Traditional session login Authentication
JS how to convert seconds into hours, minutes and seconds display
Review | categories and mechanisms of action of covid-19 neutralizing antibodies and small molecule drugs
每周小结(*63):关于正能量
检漏继电器JY82-2P
Kubernets first meeting
Weekly summary (*63): about positive energy
Leetcode question brushing record | 206_ Reverse linked list
如何获取el-tree中所有节点的父节点
How to avoid JVM memory leakage?
注释与注解