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是无序的

  • 相关阅读:
    魔法方法中的__str__和__repr__区别
    新建分类目录后,点击显示错误页面?
    3.用while和for循环分别计算100以内奇数和偶数的和,并输出。
    2.for循环实现打印1到10
    1.while循环实现打印1到10
    021_for语句
    014_运算符_字符串连接
    020_while语句
    019_增强switch语句
    018_switch语句
  • 原文地址:https://www.cnblogs.com/mylqm/p/13441146.html
Copyright © 2011-2022 走看看