美文网首页
HashMap排序

HashMap排序

作者: 你好宝宝 | 来源:发表于2020-07-25 21:09 被阅读0次
    import java.util.*;
    public class Test {
    
        public static void main(String[] args) {
            Map<Integer,String> map1=new HashMap();
            Map<String,Integer> map2=new HashMap();
    
            map1.put(2,"张三");
            map1.put(1,"李四");
            map1.put(3,"王二");
    
            map2.put("张三",2);
            map2.put("李四",3);
            map2.put("王二",1);
    
            sortByKey(map1);
            sortByValue(map2);
    
        }
        public static void sortByKey(Map<Integer,String> map){
            List<Map.Entry<Integer,String>> list=new ArrayList<Map.Entry<Integer,String>>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<Integer,String>>() {
                @Override
                public int compare(Map.Entry<Integer,String> o1, Map.Entry<Integer,String> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            });
    
            for(Map.Entry entry :  list){
                System.out.println("key:"+entry.getKey() + "value:"+entry.getValue());
            }
        }
    
        public static void sortByValue(Map<String,Integer> map){
            List<Map.Entry<String,Integer>> list=new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                @Override
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            });
    
            for(Map.Entry entry :  list){
                System.out.println("key:"+entry.getKey() + "value:"+entry.getValue());
            }
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:HashMap排序

          本文链接:https://www.haomeiwen.com/subject/imomlktx.html