项目有个根据日期排序的难题。我已把查好的数据封装到了list中。日期存的是字符串类型。同事想出的办法。附上代码
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import java.util.Comparator
public class ComparatorArea implements Comparator {
Map<String, Integer> sortValue = new HashMap<String, Integer>();
public int compare(Object p1, Object p2) {
Object o1 = ((Map) p1).get("classDate").toString()+" "+((Map) p1).get("classtime").toString();
Object o2 = ((Map) p2).get("classDate").toString()+" "+((Map) p1).get("classtime").toString();
String key1 = o1 != null ? o1.toString() : "";
String key2 = o2 != null ? o2.toString() : "";
if (StringUtils.isEmpty(key1) && StringUtils.isEmpty(key2)) {
return 0;// 都为null或空串,相等
} else if (key1.equals(key2)) {
return 0;
} else if (StringUtils.isEmpty(key1) && !StringUtils.isEmpty(key2)) {
return 1;// null或空串越向后靠
} else if (!StringUtils.isEmpty(key1) && StringUtils.isEmpty(key2)) {
return -1;// null或空串越向后靠
} else if (key1.compareTo(key2) > 0) {
return -1;// null或空串越向后靠
} else if (key1.compareTo(key2) == 0) {
return 0;// null或空串越向后靠
} else if (key1.compareTo(key2) < 0) {
return 1;// null或空串越向后靠
} else {
return -1;
}
}
}
//用法
ComparatorArea comparator = new ComparatorArea();
Collections.sort(list,comparator);//这里存放已经封装好的要排序的list
System.out.println(list.toString());//之后直接对list进行输出即可
需要另外导入一个包。StringUtils是struts中的common-logging包