【发布时间】: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.<Map.Entry<String, Long>, Long>comparing(Map.Entry::getValue)).reversed())或者更好:sorted((Map.Entry.<String, Long>comparingByValue()).reversed())
标签: java java-8 java-stream comparator