Misunderstanding about Comparator in java 8

后端 未结 1 494
予麋鹿
予麋鹿 2021-01-11 14:17
public class Test {
    public static void main(String[] args) {
        List> list = new ArrayList<>();
        list.add(new         


        
相关标签:
1条回答
  • 2021-01-11 15:10

    I believe it's just that type inference is failing, basically - because the reverse() call gets in the way of the expected argument type of sorted() and the lambda expression.

    You can do it if you specify the type to comparingInt explicitly:

    list.stream()
        .sorted(Comparator.<Pair<String, Integer>>comparingInt(p -> p.v).reversed())
        .map(p -> p.k)
        .forEach(System.out::println);
    

    Or if you just declare the comparer first:

    Comparator<Pair<String, Integer>> forward = Comparator.comparingInt(p -> p.v);
    list.stream()
        .sorted(forward.reversed())
        .map(p -> p.k)
        .forEach(System.out::println);
    

    It feels to me like there should be a Stream.reverseSorted so make this sort of thing really easy, but it doesn't look like it exists :(

    0 讨论(0)
提交回复
热议问题