繁体   English   中英

使用 Comparator.reversed() 反转 stream 的排序顺序

[英]Reversing sorting order of a stream using Comparator.reversed()

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

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

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

编辑:我将 map 的键和值混合在一起并对其进行了编辑。 由于我的错误,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()));
    }
}

示例运行:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM