Reputation: 183
How can I collect stream to collection with diamonds?
For example, previously I had code like this for singleton list, but for now I can have more than one element.
private static final GrantedAuthority userAuthority = new SimpleGrantedAuthority("ROLE_USER");
private static final Collection<? extends GrantedAuthority> defaultUserAuthorities =
Collections.singletonList(userAuthority);
And I trying to do like this, but stuck with Collectors.
Collection<? extends GrantedAuthority> collect = user.getRoles().stream()
.map(r -> r.getName().name())
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toCollection(/*What should be here?*/));
How can I collect to this Collection<? extends GrantedAuthority>
?
Upvotes: 0
Views: 77
Reputation: 40072
You can also just use a List<? extends GrantedAuthority>
as List extends Collection
.
List<? extends GrantedAuthority> list = user.getRoles().stream()
.map(r -> r.getName().name())
.map(SimpleGrantedAuthority::new)
.toList();
Note that Collection
does not have the get
and add
methods that are provided by List
, assuming you want to retrieve and/or set the values.
Upvotes: 2
Reputation: 89404
.collect(Collectors.toList())
can be used, as a List
is a Collection
.
Upvotes: 2