// c_name 要排序的字段,totalAmt_ord&&status_ord,一个是Double,一个是String,c_value是升序或者降序
public static List getDisplayList(Map map ,String c_name,String c_value) {
if(map==null) return null ;
List tList = new ArrayList();
for(Iterator it=map.keySet().iterator();it.hasNext();){
String key = it.next().toString();
Object o = map.get(key);
String rs = key+"&&"+o ;
tList.add(rs);
}
Collections.sort(tList,new MapComparator(c_name,c_value));
return getListKey(tList);
}
// 解析List,得到存Key的List
public static List getListKey(List list) {
if(list==null) return null ;
List result = new ArrayList();
for(int i=0;i<list.size();i++) {
String key = (String)list.get(i);
result.add(key.split("&&")[0]);
}
return result ;
}
// Comparator 的实现
public class MapComparator implements Comparator {
private String c_name ;
private String c_value ;
MapComparator(){
}
MapComparator(String name,String value) {
c_name = name ;
c_value = value ;
}
public int compare(Object o1, Object o2) {
String s1 = getRecord(o1);
String s2 = getRecord(o2);
if("totalAmt_ord".equals(c_name)) {
double v1 = Double.parseDouble(s1);
double v2 = Double.parseDouble(s2);
if("ASC".equals(c_value)) {
if(v1>=v2) return 1;
else return -1;
}else {
if(v1<v2) return 1;
else return -1;
}
}
if("status_ord".equals(c_name)) {
if("ASC".equals(c_value)) {
if(s1.compareTo(s2)>=0) return 1;
else return -1;
}else {
if(s1.compareTo(s2)<0) return 1;
else return -1;
}
}
return 0;
}
public String getRecord(Object o){
String[] str = ((String)o).split("&&");
return str[1];
}
}
要求是通过对Map里的value值进行升序或者降序排序,最终能够得到排序后的key,value。
网上查了许多相关资料,没有找到简单明了的,只能自己笨办法写了个。Map类型是<String,String>或者<String,Double>,先把Key和value连成一个字符串,用的是“&&”分割,放入一个List中,然后对List排序(comparator中队该字符串解析,得到value值),再排序后的List处理,得到存key的有序List,最后可以通过对该List遍历得到有序的Key或者value。——此处没有考虑效率问题