java 对map中的 value 排序

package Map;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class SortMap {
       public static void main(String[] args) {
      Map map=new TreeMap ();
      map.put("图书" , 4);
      map.put("音像" , 6);
      map.put("素材" , 9);
      map.put("音乐" , 8);
      map.put("影视" , 7);
      map.put("动漫" , 4);
      map.put("歌曲" , 3);
      map.put("图片" , 2);
      map.put("图标" , 6);
      ArrayList<Map.Entry<String,Integer>> entries= sortMap(map);
      for( int i=0;i<5;i++){
            System. out.print(entries.get(i).getKey()+":" +entries.get(i).getValue());
      }
      }
    public static ArrayList<Map.Entry<String,Integer>> sortMap(Map map){
     List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
     Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
         public int compare(Map.Entry<String, Integer> obj1 , Map.Entry<String, Integer> obj2) {
             return obj2.getValue() - obj1.getValue();
         }
     });
      return (ArrayList<Entry<String, Integer>>) entries;
    }
}


此时是按照降序排序,如果想升序排序,则Comparator的 返回 改为obj1.getValue() - obj2.getValue();即可


总结:由于TreeMap主要是针对key进行默认排序的,但是有的时候我们需要对value进行排序,这时候主要采取的策略是 将map变为List,然后利用Collections.sort进行排序,同时重写Comparator方法,即可。

猜你喜欢

转载自lhkzyz.iteye.com/blog/1666193