【问题标题】:Compare hashmap by both key and value in Java 8 using lambda function使用 lambda 函数在 Java 8 中按键和值比较 hashmap
【发布时间】:2021-04-04 23:47:49
【问题描述】:

我是 java 8 的新手,想编写一个函数,按值对 hashmap 进行排序,如果值是按键排序的相同。

按值对哈希图进行排序:

Map<String, Integer> map1 = new LinkedHashMap<>();
                 map.entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEachOrdered(x -> map1.put(x.getKey(), x.getValue()));       
    map1.forEach((k,v) ->{ System.out.println(k +" "+v);} );

我使用过 Python 3,它使用 mapSorted = sorted(map.items()key = lambda item : (item[1], item[0])) 对键和值进行排序。 Java 8 中有类似的东西吗?

【问题讨论】:

    标签: java sorting lambda java-8 comparator


    【解决方案1】:

    您期待的 API 是 Comparator#thenComparing。这种排序的实现并不简单的原因是类型推断。

    类型推断需要一些帮助,例如:

    Comparator.comparing(Map.Entry<String, Integer>::getValue)
                        .reversed().thenComparing(Map.Entry::getKey)
    

    除此之外,您最好将输出收集到保留顺序的 Map 中,否则,排序会浪费计算。因此,这样的事情应该起作用:

    LinkedHashMap<String, Integer> sortedMap = map.entrySet()
                .stream()
                .sorted(Comparator.comparing(Map.Entry<String, Integer>::getValue)
                        .reversed().thenComparing(Map.Entry::getKey))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (a, b) -> a, LinkedHashMap::new));
    

    【讨论】:

    【解决方案2】:

    定义你的地图

            HashMap<String, Integer>map1 = new HashMap();
            map1.put("aa",5);
            map1.put("bbb",2);
            map1.put("ccccc",2);
            map1.put("dddddd",3);
    

    排序,如果你想和字符串比较你需要自己定义它

            List<Entry<String, Integer>> collect = map1.entrySet().stream().sorted(new Comparator<Entry<String, Integer>>(){
                @Override
                public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                    int ll=0;
                    if (o1.getValue()>o2.getValue()){
                        ll=-1;
                    }
                    else if(o1.getValue()<o2.getValue()){
                        ll=1;
                    }
                    else if (o1.getKey().length()>o2.getKey().length()) {
                        ll=-1;
                    }
                    else if (o1.getKey().length()<o2.getKey().length()) {
                        ll=1;
                    };
                    return ll;
                }
            }).collect(Collectors.toList());
    

    结果类似于 [aa=5, dddddd=3, ccccc=2, bbb=2]

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2016-11-08
      相关资源
      最近更新 更多