Ebr*_*rin 3 java comparator java-8 java-stream
我正在编写一个程序,读取一个字符串作为输入,然后输出 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()));
}
Run Code Online (Sandbox Code Playgroud)
编辑:我已经将地图的键和值混合并进行了编辑。由于我的错误,Arvind 的答案可能看起来有点不同,但这并不重要,因为 Map.Entry 同时具有 .comparingByKey 和 .comparingByValue 方法。
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()));
}
}
Run Code Online (Sandbox Code Playgroud)
示例运行:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1036 次 |
| 最近记录: |