码迷,mamicode.com
首页 > 编程语言 > 详细

java根据HashMap中的值将其元素排序

时间:2017-02-04 23:05:41      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:compare   list   没有   span   str   例子   com   hash   val   

思路:HashMap或Map本身没有排序功能,若要进行较轻松的排序,可利用ArrayList中的sort方法

例子:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapSorter {

    public static void main(String[] args){
        
        Map<String, Integer> map = new HashMap<String, Integer>();
        List<Map.Entry<String, Integer>> list = new ArrayList<>();
        
        map.put("Five", 5);
        map.put("Seven", 7);
        map.put("Eight", 8);
        map.put("One",1);
        map.put("Two",2);
        map.put("Three", 3);
        
        for(Map.Entry<String, Integer> entry : map.entrySet()){
             list.add(entry); //将map中的元素放入list中
        }

        list.sort(new Comparator<Map.Entry<String, Integer>>(){
              @Override
               public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return o2.getValue()-o1.getValue();} 
                   //逆序(从大到小)排列,正序为“return o1.getValue()-o2.getValue”
        }); 
        
        for(Map.Entry<String, Integer> entry: list){
              System.out.println(entry);
        }
    }
}

/*
* 输出结果:
* Eight=8
* Seven=7
* Five=5
* Three=3
* Two=2
* One=1
*/

java根据HashMap中的值将其元素排序

标签:compare   list   没有   span   str   例子   com   hash   val   

原文地址:http://www.cnblogs.com/ticktack/p/6366480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!