Collections.emptyList() 和 Collections::emptyList 有什么区别

Ara*_*raf -1 java java-8 java-stream method-reference

编码时使用java流显示错误

Optional.ofNullable(product.getStudents())
                .orElseGet(Collections.emptyList())
                .stream().map(x->x.getId)
                .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

此代码显示以下错误 错误

不兼容的类型,必需的供应商> 但空列表被干扰到 List : 不存在 T 类型变量的实例,因此 List 符合供应商>

但是如果我替换Collections.emptyList()WITH Collections::emptyList It 就完美了。

Collections.emptyList() 与 Collections::emptyList 有什么区别?

Era*_*ran 7

Collections.emptyList()是一个static返回 a的方法List<T>,即表达式Collections.emptyList()将执行该emptyList()方法,其值将是 a List<T>。因此,您只能将该表达式传递给需要List参数的方法。

Collections::emptyList 是一个方法引用,它可以实现单个方法具有匹配签名的功能接口。

ASupplier<List<T>>是一个函数式接口,它有一个返回 a 的方法List<T>,该方法与 的签名匹配Collections.emptyList()。因此,在您的示例中需要 a的方法(例如Optional's )可以接受可以实现该接口的方法引用。orElseGet(Supplier<? extends T> other)Supplier<? extends List<Student>>Collections::emptyList

  • 我想说 `Collections.emptyList()` 是一个调用该方法并产生一个 `List` 的表达式 (5认同)