如何将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
相关产品推荐
相关产品推荐

