1. 程式人生 > >怎麼實現對Map的值進行排序?

怎麼實現對Map的值進行排序?

我們知道Map是以鍵值對的介面,他的實現子類主要是:

1、Hashtable:底層是雜湊表資料結構,不可以存入空鍵和空值,執行緒是同步的,在JDK1.0版本出現,

2、HashMap:底層是雜湊表資料結構,可以存入空鍵和空值,執行緒是不同步的,在JDK1.2版本出現所以效率方面比Hashtable高

3、TreeMap:底層是二叉樹資料結構,支援鍵的自然排序,執行緒是不同步的,

按key排序:

class Demo{

public static void main(String[] args){

TreeMap<String,String> map = new TreeMap<String,String>(new Comparator<String>(){
public int compare(String a,String b){
return a.compareTo(b);
}
});


map.put("b","B");
map.put("a","A");
map.put("c","C");
map.put("d","D");


for(Map.Entry<String, String> me :map.entrySet()){
System.out.println(me.getKey()+":"+me.getValue());
}

}

}

按value排序:

class Demo{

public static void main(String[] args){

HashMap<Integer,String> map = new HashMap<Integer,String>();

map.put(new Integer(2), "a");
map.put(new Integer(5), "c");
map.put(new Integer(1), "b");
map.put(new Integer(3), "aa");

List<Map.Entry<Integer,String>> li = new ArrayList<Map.Entry<Integer,String>>(
map.entrySet());


Collections.sort(li,new Comparator<Map.Entry<Integer,String>>(){
public int compare(Entry<Integer,String> a,Entry<Integer,String> b){
return a.getValue().compareTo(b.getValue());
}
});
for(Map.Entry<Integer,String> me : li){
System.out.println(me.getKey()+":"+me.getValue());
}

}

}