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

ada*_*ase 57 java collections lambda java-8 java-stream

我有地图Map<Type, Long> countByType,我希望有一个列表,它按相应的值排序(最小到最大)键.我的尝试是:

countByType.entrySet().stream().sorted().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但是这只是给我一个条目列表,如何在不丢失订单的情况下获得类型列表?

Jes*_*per 115

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

你想得到钥匙; 用于map将条目转换为键.

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

  • ...或`.sorted(Map.Entry.comparingByValue())` (40认同)

Sot*_*lis 11

您必须根据条目的值对自定义比较器进行排序.然后在收集之前选择所有键

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


小智 5

您可以使用这个作为您的问题的示例

    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);
Run Code Online (Sandbox Code Playgroud)