zoukankan      html  css  js  c++  java
  • java根据HashMap中的值将其元素排序

    思路: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
    */
  • 相关阅读:
    非vue-cli的花括号闪现问题
    vue中实现图片全屏缩放预览,支持移动端
    vue 图片预览插件
    angular.uppercase()
    angular.toJson()
    angular.module()
    对AngularJs的简单了解
    jQuery的属性、遍历和HTML操作
    JQuery函数
    JQuery的选择器
  • 原文地址:https://www.cnblogs.com/ticktack/p/6366480.html
Copyright © 2011-2022 走看看