简体   繁体   English

通过 Java 8 中的键和值比较 hashmap 使用 lambda ZC1C425268E68385D14ZA74

[英]Compare hashmap by both key and value in Java 8 using lambda function

I am new to java 8 and would like to write a function which sorts hashmap by values and if values are the same sort by keys.我是 java 8 的新手,想写一个 function 按值排序 hashmap,如果值按键排序相同。

To sort the hashmap by values:按值对 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);} );

I have worked with Python 3 and it has sorting for both keys and values using mapSorted = sorted(map.items() , key = lambda item: (item[1], item[0])) .我使用过 Python 3,它使用mapSorted = sorted(map.items() , key = lambda item: (item[1], item[0]))对键和值进行排序。 Is there something similar in Java 8? Java 8中是否有类似的东西?

The API you are looking forward to is Comparator#thenComparing .您期待的 API 是Comparator#thenComparing The reason why the implementation for such sorting is not straightforward is because of the type-inference.这种排序的实现并不简单的原因是类型推断。

The type inference needs some help which can be provided such as:类型推断需要一些帮助,例如:

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

Apart from which you shall ideally collect the output to a Map that preserves the order, otherwise, the sorting is a waste of computations.除此之外,您最好将 output 收集到保留顺序的 Map 中,否则排序是浪费计算。 Hence something like this shall work:因此,这样的事情应该起作用:

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));

define your map定义你的 map

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

sort,if you want to compare with string your need defining it by yourself排序,如果您想与字符串进行比较,您需要自己定义它

        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());

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM