• 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
    
  • 相关阅读:
    07spring-mybatis整合
    08ssm三大框架整合
    05spring_AOP
    06spring-test
    03spring初始化销毁自动装配
    04spring注解
    01spring简介入门
    02spring_IoC
    09springmvc_mybatis框架整合
    简单的搭建一个SSH框架
  • 原文地址:https://www.cnblogs.com/cyno/p/4451771.html
Copyright © 2020-2023  润新知