Comparator.reversed()编译类型推断失败

错误描述

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Client {

  public static void main(String[] args) {
    List<String> list = Arrays.asList("hello", "world", "hello cat");
    //works
    list.sort(Comparator.comparingInt(String::length));
    //works
    list.sort(Comparator.comparingInt(x -> x.length()));
    //works
    list.sort(Comparator.comparingInt((String x) -> x.length()).reversed());
    //not works
    list.sort(Comparator.comparingInt(x -> x.length()).reversed());
    System.out.println(list);
  }

}

/**
     * Returns a comparator that imposes the reverse ordering of this
     * comparator.
     *
     * @return a comparator that imposes the reverse ordering of this
     *         comparator.
     * @since 1.8
     */
    default Comparator<T> reversed() {
        return Collections.reverseOrder(this);
    }

前面几种情况可以正常编译,第四种情况编译不通过,这种情况编译器不能推断出字符串类型,只能当做Object类型。

解决方法

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Client {

  public static void main(String[] args) {
    List<String> list = Arrays.asList("hello", "world", "hello cat");
    //works
    list.sort(Comparator.comparingInt((String x) -> x.length()).reversed());
    //works
    list.sort(Collections.reverseOrder(Comparator.comparingInt(x -> x.length())));
    //works
    list.sort(Comparator.comparing(x -> x.length(), Comparator.reverseOrder()));
    System.out.println(list);
  }

}

显式声明类型或者使用Collections.reverseOrder()方法。

参考

Comparator.reversed() does not compile using lambda
Comparator.reversed() should be usable in static context

posted @ 2021-04-11 12:05  strongmore  阅读(1112)  评论(0编辑  收藏  举报