为了账号安全,请及时绑定邮箱和手机立即绑定

“错误:不兼容的类型:推理变量 R 具有不兼容的边界”当 flatMap 单行中的流

“错误:不兼容的类型:推理变量 R 具有不兼容的边界”当 flatMap 单行中的流

扬帆大鱼 2021-12-10 14:43:23
我有一个自定义类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>正确
查看完整描述

2 回答

?
开满天机

TA贡献1786条经验 获得超13个赞

你可以这样做:


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>类型变量时的预期返回类型。


查看完整回答
反对 回复 2021-12-10
?
慕森王

TA贡献1777条经验 获得超3个赞

这应该可以解决问题:

Set<Long> collectSet = customs.stream()
                           .flatMap(x -> x.getIds().stream())
                           .collect(Collectors.toSet());

您正在尝试将 a 转换Set为 a List,这是不可能的。



查看完整回答
反对 回复 2021-12-10
  • 2 回答
  • 0 关注
  • 1011 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号