怎么实现对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());
}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值