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

Java 8 stream map to list of keys sorted by values

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

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

然而,这只是给了我一个条目列表,我怎样才能得到一个类型列表,而不丢失顺序?

您必须根据条目的值使用自定义比较器进行排序。然后select收集前的所有key

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

你说你想按值排序,但你的代码中没有。将 lambda(或方法引用)传递给 sorted 以告诉它您希望如何排序。

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

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

您可以按如下所示按值对地图进行排序,更多示例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()));

这是 StreamEx

的简单解决方案
EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();
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());

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

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

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