类ComparatorList
import java.util.Comparator;
import java.util.Map;
public class ComparatorList implements Comparator{
private String compareStr;
public ComparatorList(){
}
public
ComparatorList(String compareStr){
this.compareStr=compareStr;
}
@Override
public int compare(Object o1, Object o2) {
int flag2=0;
Map map1=(Map)o1;
Map map2=(Map)o2;
System.out.println("map1.get(compareStr):"+map1.get(compareStr));
System.out.println("map2.get(compareStr):"+map2.get(compareStr));
int
flag=String.valueOf(map1.get(compareStr)).compareTo(String.valueOf(map2.get(compareStr)));
//倒序
if(flag>0){
flag2=-1;
}else if(flag<0){
flag2=1;
}
System.out.println(flag2);
return flag2;
}
}
类Test3
package com.mrlun.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.emory.mathcs.backport.java.util.Collections;
public class Test3 {
public void test(){
}
public static void main(String[] args) {
Map map3=new HashMap();
map3.put("fruits", "apple");
map3.put("eat_time", "20140721
00:01:29");
Map map1=new HashMap();
map1.put("fruits",
"orange");
map1.put("eat_time", "20140720
00:20:29");
Map map2=new HashMap();
map2.put("fruits", "pear");
map2.put("eat_time", "20140721
00:05:29");
List list=new
ArrayList();
list.add(map1);
list.add(map2);
list.add(map3);
Collections.sort(list,new
ComparatorList("eat_time"));
for(Object o:list ){
Map
m=(Map)o;
System.out.println(m.get("fruits")+":"+m.get("eat_time"));
}
}
}
// output:
pear:20140721 00:05:29
apple:20140721 00:01:29
orange:20140720 00:20:29
总结:
要想实现自己的比较器,就要实现java提供的Comparator接口,并且覆盖其compare方法,返回值有-1、0、1,分别表示比较的结果,默认是升序排列,要想实现倒序,则要加上特殊处理的代码,如上。