Java 8 流映射到按值排序的键列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30425836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:37:03  来源:igfitidea点击:

Java 8 stream map to list of keys sorted by values

javacollectionslambdajava-8java-stream

提问by adaPlease

I have map Map<Type, Long> countByTypeand I want to have a list which has sorted (min to max) keys by their corresponding values. My try is:

我有地图Map<Type, Long> countByType,我想要一个列表,该列表已按相应的值对(最小到最大)键进行排序。我的尝试是:

countByType.entrySet().stream().sorted().collect(Collectors.toList());

however this just gives me a list of entries, how can I get a list of types, without losing the order?

然而,这只是给了我一个条目列表,我怎样才能在不丢失订单的情况下获得类型列表?

采纳答案by Jesper

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sortedto tell it how you want to sort.

你说你想按值排序,但你的代码中没有。传递一个 lambda(或方法引用)sorted来告诉它你想如何排序。

And you want to get the keys; use mapto transform entries to keys.

而你想拿到钥匙;用于map将条目转换为键。

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

回答by Sotirios Delimanolis

You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting

您必须根据条目的值使用自定义比较器进行排序。然后在收集之前选择所有密钥

countByType.entrySet()
           .stream()
           .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
           .map(e -> e.getKey())
           .collect(Collectors.toList());

回答by Ajay Kumar

You can sort a map by value as below, more example here

您可以按值对地图进行排序,如下所示,更多示例在这里

//Sort a Map by their Value.
Map<Integer, String> random = new HashMap<Integer, String>();

random.put(1,"z");
random.put(6,"k");
random.put(5,"a");
random.put(3,"f");
random.put(9,"c");

Map<Integer, String> sortedMap =
        random.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

回答by user_3380739

Here is the simple solution with StreamEx

这是StreamEx的简单解决方案

EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();

回答by Kannan Msk

Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "A");

List<String> list = map.values().stream()
    .sorted()
    .collect(Collectors.toList());

Output: [A, B, C, D]

输出: [A, B, C, D]

回答by MADHUR GUPTA

You can use this as an example of your problem

你可以用这个作为你的问题的例子

    Map<Integer, String> map = new HashMap<>();
    map.put(10, "apple");
    map.put(20, "orange");
    map.put(30, "banana");
    map.put(40, "watermelon");
    map.put(50, "dragonfruit");

    // split a map into 2 List
    List<Integer> resultSortedKey = new ArrayList<>();
    List<String> resultValues = map.entrySet().stream()
            //sort a Map by key and stored in resultSortedKey
            .sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
            .peek(e -> resultSortedKey.add(e.getKey()))
            .map(x -> x.getValue())
            // filter banana and return it to resultValues
            .filter(x -> !"banana".equalsIgnoreCase(x))
            .collect(Collectors.toList());

    resultSortedKey.forEach(System.out::println);
    resultValues.forEach(System.out::println);