Search code examples
javajava-streamconsumersupplier

Correct use of Java 8 supplier consumer


I'm still strugling with Suppliers and Consumers for Java 8, I have this:

final Set<String> roles = new HashSet<>();
user.getRoleGroups().forEach(rg -> rg.getRoles().forEach(r -> roles.add(r.getName())));

To get a Set from role names that are inside a list of Roles inside a list of RoleGroups. Pretty sure I could use something in one line with .stream().map() and RoleGroup::getRoles and Role::getName to get this Set. But I don't know how.


Solution

  • You are pretty close! To use a Stream instead, do something like this:

    final Set<String> roles = user.getRoleGroups().stream()
       .flatMap(g -> g.getRoles().stream())
       .map(Role::getName)
       .collect(Collectors.toSet());
    

    Use of flatMap() is the only tricky part here. The flatMap() operation transforms an element to a Stream, which is concatenated with the Streams from the other elements.