You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Stream收集到带泛型通配符的Collection集合中?

解决方案

你可以直接传入具体集合实现类的构造方法引用,比如ArrayList::new,完整代码如下:

Collection<? extends GrantedAuthority> collect = user.getRoles().stream()
        .map(r -> r.getName().name())
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toCollection(ArrayList::new));

原理说明:

  • 你的Stream最终生成的元素是SimpleGrantedAuthority类型,它是GrantedAuthority的实现类。
  • Collectors.toCollection(ArrayList::new)会返回一个Collection<SimpleGrantedAuthority>,而这个类型可以安全赋值给Collection<? extends GrantedAuthority>——因为通配符? extends GrantedAuthority表示“任何包含GrantedAuthority子类元素的Collection”,SimpleGrantedAuthority正好符合这个约束。

你也可以根据需求换成其他Collection实现类的构造方法引用,比如LinkedList::new、HashSet::new等,只要是Collection的子类都可以。如果想更显式指定泛型,也可以写成:

.collect(Collectors.toCollection(() -> new ArrayList<SimpleGrantedAuthority>()));

不过方法引用的写法更简洁,编译器会自动完成类型推断。

内容的提问来源于stack exchange,提问作者Denys Bondarenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:15:29