Search code examples
javajava-stream

Stream collect to collection with diamonds


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> ?


Solution

  • .collect(Collectors.toList()) can be used, as a List is a Collection.