首页 > 解决方案 > 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 有什么区别?

标签: javajava-8java-streammethod-reference

解决方案


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


推荐阅读