来源
https://blog.51cto.com/zhaodan/1725249
//可以使用Collections.sort(List list, Comparator c)来实现
这里举例hashmap中存的一个时间的键值,按照时间的值来排序
//先写个类实现Comparator,并重写compare(Object o1, Object o2)方法,在方法中自定义比较逻辑
public class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
int result = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
HashMap<String, String> map1 = (HashMap<String, String>) o1, map2 = (HashMap<String, String>) o2;
Date map1_time = format.parse(map1.get("time"));
Date map2_time = format.parse(map2.get("time"));
if(map1_time.after(map2_time)){
result = -1;
}else if(map1_time.before(map2_time)){
result = 1;
}else if(map1_time.equals(map2_time)){
result = 0;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
}
调用的时候Collections.sort(List对象, new MyComparator());