// 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?!颂帥]有考慮效率問題
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

