如何根据hashmap里面value的值进行排序?

J2EE 码拜 9年前 (2015-07-18) 2327次浏览 0个评论

我现在有一个hashmap,可以就是字符串,value是数字,如何根据数字的大小对他进行排序使得输出时是按照value的值大小排序

#1

map  value sort

#2

很多

#3

回复1楼:

= =能不能详细点,而且我需要的只是取出前十个

30分

#4

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;
    }
}

#5

回复4楼:

小屌丝改成小萝莉…我感觉怪怪的…  

#6

回复4楼:

太棒了,就是这个,谢谢


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明如何根据hashmap里面value的值进行排序?
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!