怎么实现对Map的值进行排序?

来源:互联网 发布:java中excel导入导出 编辑:程序博客网 时间:2024/05/16 05:29

我们知道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());
}

}

}

0 0
原创粉丝点击