/**
* map 排序共用方法
* @param mapList map列表
* @param sort 排序字段
* @param order升序:asc 降序 desc
* @return
*/
public List<Map<String, Object>> sortToMap(List<Map<String, Object>> mapList, final String sort, final String order) {
Collections.sort(mapList, new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
if (o1.get(sort) instanceof String) {
String map1value = ConvertUtil.objectToString(o1.get(sort));
String map2value = ConvertUtil.objectToString(o2.get(sort));
if ("DESC".equals(order.toUpperCase())) {
return map1value.compareTo(map2value);
} else {
return map2value.compareTo(map1value);
}
} else {
Double map1value = ConvertUtil.objectToDouble(o1.get(sort));
Double map2value = ConvertUtil.objectToDouble(o2.get(sort));
if ("DESC".equals(order.toUpperCase())) {
return map1value - map2value > 0 ? 1 : 1;
} else {
return map1value - map2value > 0 ? -1 : 1;
}
}
}
});
return mapList;
}
下面是ConvertUtil 工具类里面的两个方法
/**
*将Object转换为String
*/
public static String objectToString(Object o){
if(o == null){
return "";
}else if(o instanceof String){
return (String)o;
}else if(o instanceof Integer){
return String.valueOf((Integer)o);
}else if(o instanceof Long){
return String.valueOf((Long)o);
}else if(o instanceof Double){
return String.valueOf((Double)o);
}else if(o instanceof Float){
return String.valueOf((Float)o);
}else if(o instanceof Boolean){
return String.valueOf(booleanBoInteger((Boolean)o));
}else if(o instanceof Date){
return ConvertUtil.formatDateToString((Date)o);
}
else{
return "";
}
}
/**
*将Object转换为Double
*/
public static Double objectToDouble(Object o){
if(o instanceof BigDecimal){
return ((BigDecimal) o).doubleValue();
}else if(o instanceof String){
return Double.valueOf((String)o);
}else if(o instanceof Integer){
return Double.valueOf((Integer)o);
}else if(o instanceof Double){
return (Double)o;
}else if(o instanceof Long){
return ((Long) o).doubleValue();
}else{
return 0.0;
}
}