java - “错误:不兼容的类型:推理变量 R 具有不兼容的边界”当 flatMap 单行流时
问题描述
我有一个自定义类Custom
。
public class Custom {
private Long id;
List<Long> ids;
// getters and setters
}
现在我有List<Custom>
对象了。我想转换List<Custom>
成List<Long>
. 我已经编写了如下代码,并且工作正常。
List<Custom> customs = Collections.emptyList();
Stream<Long> streamL = customs.stream().flatMap(x -> x.getIds().stream());
List<Long> customIds2 = streamL.collect(Collectors.toList());
Set<Long> customIds3 = streamL.collect(Collectors.toSet());
现在我将 line2 和 line3 组合成一行,如下所示。
List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());
现在,这段代码没有编译,我得到以下错误 -
error: incompatible types: inference variable R has incompatible bounds
List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());
^
equality constraints: Set<Long>
upper bounds: List<Long>,Object
where R,A,T are type-variables:
R extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
A extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
T extends Object declared in interface Stream
我怎样才能转换List<Custom>
成Set<Long>
或List<Long>
正确
解决方案
你可以这样做:
List<Custom> customs = Collections.emptyList();
Set<Long> customIdSet = customs.stream()
.flatMap(x -> x.getIds().stream())
.collect(Collectors.toSet()); // toSet and not toList
您收到编译器错误的原因是您使用了不正确Collector
的返回 List 而不是 Set ,这是您将其分配给类型变量时的预期返回Set<Long>
类型。
推荐阅读
- android - 在 recycleview kotlin 上实现搜索的问题
- postgresql - UNION ALL vs UNION 用于更新/返回+选择?
- c# - 相关数据导入 ViewModel
- mysql - 在 MySQL 中通过 JSON 中的 id 过滤表
- java - 无法通过代码找到简单模式验证的元素错误声明
- windows - 执行哪一个?
- linux - 当我使用 ssh 到远程服务器来 git 存储库时,如何获取该过程?
- html - React.js/html/css 中的 Div 变换和旋转动画
- php - 一段时间后如何清空 Woocommerce 购物车?
- android - echo $ANDROID_HOME 返回空白(mac os catalina)