zoukankan      html  css  js  c++  java
  • Java8Lambada表达式对Map的操作

    根据Map的键名、键值进行升序、降序:

    public class StudyMap {
    
    
         public static void main(String[] args) {
            Map<String, Integer> wordCounts = new HashMap<>();
            wordCounts.put("USA", 100);
            wordCounts.put("jobs", 200);
            wordCounts.put("software", 50);
            wordCounts.put("technology", 70);
            wordCounts.put("opportunity", 200);
    
    
            //按升序对值进行排序,使用LinkedHashMap存储排序结果来保留结果映射中元素的顺序
            Map<String, Integer> sortedByCount = wordCounts.entrySet()
                    .stream()
                    .sorted(Map.Entry.comparingByValue())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
            soutMap(sortedByCount);
    
            //sorted()方法将Comparator作为参数使用任何类型的值对映射进行排序。上面的排序可以用Comparator写成:
            //正向
            Map<String, Integer> sortedByCount3 = wordCounts.entrySet()
                    .stream()
                    .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
            soutMap(sortedByCount3);
    
            //反向 == reversed()
            Map<String, Integer> sortedByCount2 = wordCounts.entrySet()
                    .stream()
                    .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
            soutMap(sortedByCount2);
    
        }
    
        public static void soutMap(Map<String, Integer> sortedByCount){
            for (Map.Entry<String, Integer> entry : sortedByCount.entrySet()) {
                System.out.println("key:" + entry.getKey()+"\tvalue:"+entry.getValue());
            }
        }
    }

    在上述代码中对于map的重新转换,建议转换成LinkedHashMap,因为HashMap是无序的

  • 相关阅读:
    mybatis <=或这个>=提示错误Tag name expecte问题解决
    Navicat 设置自增长初始值
    mysql 时间与字符串相互转换
    jquery 动态控制显隐
    mysql 查询常见时间段数据
    jquery 取得select选中的值
    java8 运算语法集
    springboot 单元测试
    idea 自动生成并跳转单元测试
    限制页面被pc端访问
  • 原文地址:https://www.cnblogs.com/mylqm/p/13441146.html
Copyright © 2011-2022 走看看