• 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
    
  • 相关阅读:
    第一章 数据库基本操作
    Linux卸载jdk
    Jenkins Jboss的启动
    Jenkins启动脚本
    Linux SVN 创建项目
    测试工程师到底是干啥的?测试工程师转开发有多大希望?
    如何评审功能测试用例?
    Maven上传
    持续集成
    jquery获取所有checked的value
  • 原文地址:https://www.cnblogs.com/cyno/p/4451771.html
Copyright © 2020-2023  润新知