java - Collections.emptyList() 与 Collections::emptyList 有什么区别
问题描述
编码时使用java流显示错误
Optional.ofNullable(product.getStudents())
.orElseGet(Collections.emptyList())
.stream().map(x->x.getId)
.collect(Collectors.toList());
此代码显示以下错误 ERROR
不兼容的类型,必需的供应商>但空列表被干扰到列表:不存在 T 类型变量的实例,因此列表符合供应商>
但是如果我替换Collections.emptyList()
WITHCollections::emptyList
它将是完美的。
Collections.emptyList() 与 Collections::emptyList 有什么区别?
解决方案
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
推荐阅读
- c++ - 何时不从 C++ 中的构造函数中抛出异常
- amazon-web-services - 授予对 S3 存储桶内所有子文件夹的完全控制权限(不包括 parent)
- mysql - 如何在 Windows10 上的 MINGW64 中运行 MYSQL?
- vb.net - 如何覆盖默认的 SQL 迁移生成器?
- regex - ul 元素中的多行打破了我的正则表达式模式
- python - Jupyter Notebook 无法正确处理 VS Code 中的 .js 元素
- python - 在烧瓶 404、500 页上添加自定义处理程序
- javascript - 如何配置 login() 函数;使用 GET 请求?
- laravel - 登录/注册后重定向到以前的 URL 不起作用
- .net - dotnet 无法构建正在使用的 ASP.NET Core 站点