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
    
  • 相关阅读:
    hdoj1587
    欧拉定理及其应用
    hdoj1571
    hdoj1050
    POJ推荐50题
    poj2593
    hdoj1286
    hdoj1215七夕节
    我的Linux软件
    ACM题目推荐--《算法艺术与信息学竞赛》(转)
  • 原文地址:https://www.cnblogs.com/cyno/p/4451771.html
Copyright © 2011-2022 走看看