zoukankan      html  css  js  c++  java
  • Map sorted by Value

    Map can't be sorted by value

    Map can't be sorted by value , so that we can change map to List and then sort the list .

    Collections.sort( List list , Comparator<? super T> c)

    In order to keep simple style of coding , we can add the Comparator out ot main class .

    
    class listCompare implements Comparator< Map.Entry<String,Integer> >{
                public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
               
          // Must apply compareTo() functin , to have more security .
          return o1.getValue().compareTo(o2.getValue());     
        }
    }
    
    

    Code

    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 mapSortByValue{
        public static void main(String [] args){
            
            // New a Map
            
            Map<String, Integer > map = new TreeMap<String , Integer >();
            map.put("A", 4);
            map.put("C", 2);
            map.put("B", 1);
            map.put("D", 3);
            
            // Change Map to List
            
            List<Map.Entry<String,Integer> > list = new ArrayList<Map.Entry<String,Integer> >(map.entrySet());
            
            // Sorting ...
            
            Collections.sort(list, new listCompare());
            
            // print
            
            for(Map.Entry<String ,Integer >  one:list){
                System.out.println(one.getKey() + ":" + one.getValue() );
            }
            
        }    
    }
    class listCompare implements Comparator<Map.Entry<String , Integer > > {
    
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
        
    }
    
    
    B:1
    C:2
    D:3
    A:4
    
  • 相关阅读:
    迭代器与生成器
    11.30
    函数及装饰器
    C#For循环
    C#变量与数据类型
    C#输入输出
    JDK10新特性--var
    idea插件Lombok使用
    NodeJs操作文件-写入、修改、删除、追加、读取文件内容、判断文件是否存在
    mongodb多条件分页查询(mongoTemplate分页查询)
  • 原文地址:https://www.cnblogs.com/cyno/p/4451771.html
Copyright © 2011-2022 走看看