/**
* ==============================================
* Copy right 2015-2018 by ja
* ----------------------------------------------
* This is not a free software, without any authorization is not allowed to use and spread.
* ==============================================
*
* @author : Jalan
* @version : v1.0.0
* @desc : 把对象属性抽象出来,可做为参数传递
* @since : 2018/2/7 21:07
*/
@FunctionalInterface
public interface ObjectPropertyPredicate<T> {
/**
* 把属性当参数传递到方法中,由方法去处理这个属性的值做什么。
* 传参使用: o -> o.propertyName
* 接收参数方法内使用:
* 参数:ObjectPropertyPredicate<FreeReportDataVO> express
* Predicate<Object> press = (obj) -> express.getProperty(obj).toString().startsWith("测试");
* express.getProperty(obj)
* @param o
* @return
*/
Object getProperty(T o);
}
/**
* ==============================================
* Copy right 2015-2018
* ----------------------------------------------
* This is not a free software, without any authorization is not allowed to use and spread.
* ==============================================
*
* @author : Jalan
* @version : v1.0.0
* @desc : 含空值的排序工具 根据对象的某一属性值进行排序
* @since : 2018/4/18 17:39
*/
public class ComparatorUtils {
/**
* 支持NULL排序 升序
* 1、null 会排前面
*
* @param propertyPredicate 属性
* @param <T>
* @return
*/
public static <T> Comparator<T> sort(ObjectPropertyPredicate<T> propertyPredicate) {
Comparator<T> comparator = (obj1, obj2) -> {
Object v1 = propertyPredicate.getProperty(obj1);
Object v2 = propertyPredicate.getProperty(obj2);
if (v1 == v2) {
return 0;
} else if (v1 == null) {
return -1;
} else if (v2 == null) {
return 1;
}
if (v1 instanceof Integer) {
return (Integer) v1 - (Integer) v2;
} else if (v1 instanceof Date) {
return ((Date) v1).compareTo((Date) v2);
} else if (v1 instanceof BigDecimal) {
return ((BigDecimal) v1).compareTo((BigDecimal) v2);
}
return v1.toString().compareTo(v2.toString());
};
return comparator;
}
/**
* 支持NULL排序 降序
* 1、null 会排后面
*
* @param propertyPredicate 属性
* @param <T>
* @return
*/
public static <T> Comparator<T> sortDesc(ObjectPropertyPredicate<T> propertyPredicate) {
Comparator<T> comparator = (obj1, obj2) -> {
Object v1 = propertyPredicate.getProperty(obj1);
Object v2 = propertyPredicate.getProperty(obj2);
if (v1 == v2) {
return 0;
} else if (v1 == null) {
return 1;
} else if (v2 == null) {
return -1;
}
if (v1 instanceof Integer) {
return (Integer) v2 - (Integer) v1;
} else if (v1 instanceof Date) {
return ((Date) v2).compareTo((Date) v1);
} else if (v1 instanceof BigDecimal) {
return ((BigDecimal) v2).compareTo((BigDecimal) v1);
}
return v2.toString().compareTo(v1.toString());
};
return comparator;
}
}
//以下是demo
public class TestDto{
public String Code;
public Int Age;
}
public class MainTest{
public static void main(string[] args){
List<TestDto> list = new ArrayList<TestDto>();
//这里省略 集合赋值数据。。。。
//这一句话就排序完了。
list.sort(ComparatorUtils.sort(s->s.Age));
}
}