Map排序折方式有很多種,這裡隻寫兩種按鍵排序與按值排序
jdk内置的java.util包下的TreeMap<K,V>既可滿足此類需求,向其構造方法 TreeMap(Comparator<? super K> comparator) 傳入我們自定義的比較器即可實作按鍵排序。
<span style="color:#404040;">String url = Config.getXmlConstantUrl() + "/modelData/modelConstant.ac?type=" + Config.STB_PRODUT_NAME;
String xmlSavePath = UpgradeManager.XML_FILE_PATH;
//請求平台擷取ModelConstant.xml
boolean isRequestSuc = HttpUrlUtil.sendRequestGetXml(url, xmlSavePath, "ModelConstant.xml");
if(isRequestSuc){
//無異常,解析xml
constant = XmlUtil.parserXmlFile(xmlSavePath + File.separator + "ModelConstant.xml");
}
//如網絡請求未成功或解析時無xml檔案、檔案内容格式有誤解析異常 将使用預設值
if(constant == null){
constant = new TreeMap<String, String>();
for(int i = 1; i <= 8; i++){
constant.put("v" + i, "1");
}
}
//map按key排序
constant = </span><strong><span style="color:#ff0000;">sortMapByKey</span></strong><span style="color:#404040;">(constant);
StringBuilder builder = new StringBuilder();
for(Entry<String, String> mapTemp : constant.entrySet()){
builder.append(mapTemp.getKey() + ":" + mapTemp.getValue() + ",");
}</span>
/**
* 使用 Map按key進行排序
* @param map
* @return
*/
public static Map<String, String> sortMapByKey(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortMap = new TreeMap<String, String>(
new Comparator<String>() {
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
});
sortMap.putAll(map);
return sortMap;
}
按值排序
将待排序Map中的所有元素置于一個清單中,接着使用Collections的一個靜态方法 sort(List<T> list, Comparator<? super T> c)
來排序清單,同樣是用比較器定義比較規則。排序後的清單中的元素再依次裝入Map,為了肯定的保證Map中元素與排序後的List中的元素的順序一緻,使用了LinkedHashMap資料類型。
public class Test {
public static void main(String[] args) {
Map<String,String> map = new TreeMap<String,String>();
map.put("AAA","aaa");
map.put("BBB","bbb");
map.put("CCC","ccc");
map = sortMapByValue(map);
}
private static Map<String, String> sortMapByValue(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
map.entrySet());
Collections.sort(entryList,new Comparator<Map.Entry<String,String>>() {
public int compare(Entry<String, String> o1,
Entry<String, String> o2) {
// TODO Auto-generated method stub
return o1.getValue().compareTo(o2.getValue());
}
});
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
}