Implementing a loop with Java functional programming

private List<String> getPermissoes(TipoUsuario tipoUsuario) {

    List<String> permissoes = new ArrayList();
    for (Permissao permissao : tipoUsuario.getPermissoes()) {
    return permissoes;

I'd like to implement it there with more style using functional programming. I tried the following ...

tipoUsuario.getPermissoes().stream().map(permissao -> Permissao::getNome()).collect();

It's wrong, I know, but the idea is this. Help please.

asked by anonymous 09.07.2018 / 20:57

1 answer


The syntax of Permissao::getNome is a method reference >, ie a reference to the getNome method of the Permissao class. It is different from a method call, so it can not be in the lambda body.

To use method reference , you simply use it without the parentheses.

Additionally, the collect " needs to receive some sink for it to know what type should be returned. In the class already has multiple collectors ready. For example, if you want to return the names in a list, simply use Collectors.toList() ". Example:

List<String> nomes = tipoUsuario.getPermissoes().stream()

Another alternative is to call the getNome() method instead of using the method reference , and in this case it would look like this:

List<String> nomes = tipoUsuario.getPermissoes().stream()
    .map(permissao -> permissao.getNome()).collect(Collectors.toList());
09.07.2018 / 21:05