【问题标题】:Reversing sorting order of a stream using Comparator.reversed()使用 Comparator.reversed() 反转流的排序顺序
【发布时间】:2021-06-18 06:39:33
【问题描述】:

我正在编写一个程序,它读取一个字符串作为输入,然后输出 10 个重复次数最多的单词。问题是,我的顺序颠倒了。我想从最高到最低输出,并以相反的顺序排序。所以我一直在寻找解决方案,我发现的唯一东西是 .reversed() 方法,但它说“不能从静态上下文引用非静态方法”。我不明白这个错误,因为在示例中它是在类似情况下使用的。

我是流的新手,所以我想知道解决此问题的简单方法。

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        List<String> words = Arrays.asList(input.split(" "));
        words.stream()
                .map(word -> word.replaceAll("[^A-Za-z0-9]", ""))
                .map(String::toLowerCase)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .sorted(Comparator.comparing(Map.Entry::getValue).reversed()) // static method can't be referenced
                .limit(10)
                .sorted(Comparator.comparing(Map.Entry::getKey))
                .forEach(e -> System.out.println(e.getKey()));
    }

编辑:我将地图的键和值混合在一起并对其进行了编辑。由于我的错误,Arvind 的答案可能看起来有点不同,但这并不重要,因为 Map.Entry 有 .comparingByKey 和 .comparingByValue 方法。

【问题讨论】:

  • 除了下面的答案,你还可以使用sorted((Comparator.&lt;Map.Entry&lt;String, Long&gt;, Long&gt;comparing(Map.Entry::getValue)).reversed())或者更好:sorted((Map.Entry.&lt;String, Long&gt;comparingByValue()).reversed())

标签: java java-8 java-stream comparator


【解决方案1】:

Map.Entry.comparingByKey

您可以将Comparator.reverseOrder() 传递给Map.Entry.comparingByKey

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;

class Main {
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
         String input = scanner.nextLine();
         List<String> words = Arrays.asList(input.split(" "));
         words.stream()
                 .map(word -> word.replaceAll("[^A-Za-z0-9]", ""))
                 .map(String::toLowerCase)
                 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                 .entrySet()
                 .stream()
                 .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 
                 .limit(10)
                 .sorted(Comparator.comparing(Map.Entry::getValue))
                 .forEach(e -> System.out.println(e.getKey()));
    }
}

示例运行:

1 2 3 4 5 6 7 8 9 1 2 5 9 2 7 2 3 9 5 3 1 8 3 6 8 2 3 6 9
4
7
8
6
5
1
9
3
2

【讨论】:

  • 值得注意的是为什么它有效而问题的代码无效。类型推断在链式方法调用方面存在局限性,而对于嵌套调用则没有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 2015-12-20
  • 2018-11-11
  • 2016-05-08
  • 1970-01-01
  • 2017-10-04
相关资源
最近更新 更多