java Map排序(按key和按value)

来源:互联网 发布:c 游戏编程入门 编辑:程序博客网 时间:2024/06/10 12:26

1、按照key排序

 

对于java中Map的排序,有排序Map,比如TreeMap,对于这个Map,首先只能按照键排序,其次再put和remove的时候由于需要排序,性能上会有所牺牲。

 

这种方案,使用hashmap进行创建和添加,如果需要按照key排序,则可以将该hashmap作为参数传递到new TreeMap(hashmap),则可以完成按照key的排序

 

Java代码 复制代码 收藏代码
  1. TreeMap treemap = new TreeMap(hashmap);  
 

2、按照value排序

 

使用hashmap,然后添加比较器,进行排序

 

Java代码 复制代码 收藏代码
  1. Map<String, Integer> keyfreqs = new HashMap<String, Integer>();   
  2.   
  3. ArrayList<Entry<String,Integer>> l = new ArrayList<Entry<String,Integer>>(keyfreqs.entrySet());     
  4.            
  5.         Collections.sort(l, new Comparator<Map.Entry<String, Integer>>() {     
  6.             public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {     
  7.                 return (o2.getValue() - o1.getValue());     
  8.             }     
  9.         });   
  10.            
  11.         for(Entry<String,Integer> e : l) {   
  12.             System.out.println(e.getKey() + "::::" + e.getValue());   
  13.         }  
 

当然比较器按照个人需求写。这只是简单的key是string,然后按照拼音排序,value是int,按照大小排序。。

 

0 0