Implementing a loop with Java functional programming

7
private List<String> getPermissoes(TipoUsuario tipoUsuario) {

    List<String> permissoes = new ArrayList();
    for (Permissao permissao : tipoUsuario.getPermissoes()) {
        permissoes.add(permissao.getNome());
    }        
    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

10

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 java.util.stream.Collectors 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()
    .map(Permissao::getNome).collect(Collectors.toList());

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