Java中Map根据键(Key)或者值(Value)进行排序

我们都知道,java中的Map结构是key-->value键值对存储的,而且根据Map的特性,同一个Map中不存在两个Key相同的元素,而value不存在这个限制。换句话说,在同一个Map中的Key是唯一的,而value不唯一。Map是一个接口 ,我们不能直接声明一个Map类型的对象,在实际开发中,比较常用的Map数据结构是HashMap和TreeMap,它们都是Map的直接子类。如果考虑到存取效率的话,建议使用HashMap数据结构,而如果需要考虑到Key的顺序,建议使用TreeMap,但是TreeMap在删除、添加过程中需要排序,性能比较差。


以Key进行排序

(1.1):我们可以声明一个TreeMap对象

[java]  view plain  copy
  1. Map<Integer, Person> map = new TreeMap<Integer, Person>()  

(1.2): 然后往map中添加元素,通过输出结果,可以发现map里面的元素都是排好序的:

[java]  view plain  copy
  1. //遍历集合  
  2. for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) {  
  3.     Person person = map.get(it.next());  
  4.     System.out.println(person.getId_card() + " " + person.getName());  
  5. }  

(2): 我们也可以声明一个HashMap对象,然后把HashMap对象赋值给TreeMap,如下:

[java]  view plain  copy
  1. Map<Integer, Person> map = new HashMap<Integer, Person>();  
  2. TreeMap treemap = new TreeMap(map);  
注:以上两种方式队可以轻松实现对key值进行排序。


以value进行排序

(1):先声明一个HashMap对象:

[java]  view plain  copy
  1. Map<String, Integer> map = new HashMap<String, Integer>();  
(2): 将Ma集合转换成List集合,最后借助Collections工具类进行排序

[java]  view plain  copy
  1. List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(map.entrySet())  
(3): 通过Collections.sort(List list,Comparator c)方法进行排序,代码如下:

[java]  view plain  copy
  1. Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {  
  2.     public int compare(Map.Entry<String, Integer> o1,  
  3.             Map.Entry<String, Integer> o2) {  
  4.         return (o2.getValue() - o1.getValue());  
  5.     }  
  6. });  
注:这样就实现了Map中的value按逆序排序,如果需要升序排的话,只需要修改o2.getValue()-o1.getValue()为o1.getValue()-o2.getValue()即可。


文章来自: 过往记忆 http://www.iteblog.com/archives/484
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值