java对象排序的两种方法
1.传入List对象的列表 排序的数组和升降序进行排序
public static <T> List<T> sort(List<T> list, final String[] properties, final String[] sorts) {
String[] methods = getMethodName(properties);
if (methods != null && methods.length > 0) {
for (int i = properties.length - 1; i >= 0; i--) {
final String method = methods[i];
String tmpSort = ASC;
if (sorts != null && sorts.length > i && sorts[i] != null) {
tmpSort = sorts[i];
}
final String sort = tmpSort;
list.sort(new Comparator<T>() {
@Override
public int compare(Object a, Object b) {
int ret = 0;
try {
Method m1a = a.getClass().getMethod(method);
Method m1b = b.getClass().getMethod(method);
Object obj1a = m1a.invoke(a);
Object obj1b = m1b.invoke(b);
if (obj1a == null && obj1b == null) {
return 0;
}
if (obj1a == null || obj1b == null) {
if (sort != null && DESC.equals(sort)) {
if (obj1a == null) {
ret = -1;
}
if (obj1b == null) {
ret = 1;
}
} else {
if (obj1a == null) {
ret = 1;
}
if (obj1b == null) {
ret = -1;
}
}
return ret;
}
if (obj1a instanceof Integer && obj1b instanceof Integer) {
ret = ((Integer) obj1a).compareTo((Integer) obj1b);
} else if (obj1a instanceof Double && obj1b instanceof Double) {
ret = ((Double) obj1a).compareTo((Double) obj1b);
} else if (obj1a instanceof Float && obj1b instanceof Float) {
ret = ((Float) obj1a).compareTo((Float) obj1b);
} else if (obj1a instanceof Long && obj1b instanceof Long) {
ret = ((Long) obj1a).compareTo((Long) obj1b);
} else {
ret = obj1a.toString().compareTo(obj1b.toString());
}
//倒序
if (sort != null && DESC.equals(sort)) {
return -ret;
//正序
} else {
return ret;
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return ret;
}
});
}
}
return list;
}
2.JDK1.8后可用Stream流提供的方法进行排序,具体使用如下:
list.stream().sorted(Comparator.comparing(Entity::getId).thenComparing(Entity::getName)).collect(Collectors.toList());