Implement Java Functional Programming Loop

Asked

Viewed 166 times

6

private List<String> getPermissoes(TipoUsuario tipoUsuario) {

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

I would like to implement this ai with more style using functional programming. I tried the following...

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

It’s wrong, I know, but that’s the idea. Please help.

1 answer

13


The syntax Permissao::getNome is a method Reference, or a reference to the method getNome class Permissao. It’s different from a method call, so it can’t be in the body of lambda.

To use the method Reference, just use it without the parentheses.

In addition, the method collect need to receive some collector for it to know which type should be returned. In class java.util.stream.Collectors already have several Ollectors ready. For example, if you want to return the names in a list, just use Collectors.toList(). Example:

List<String> nomes = tipoUsuario.getPermissoes().stream()
    .map(Permissao::getNome).collect(Collectors.toList());

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

List<String> nomes = tipoUsuario.getPermissoes().stream()
    .map(permissao -> permissao.getNome()).collect(Collectors.toList());
  • Perfect. That’s what I call more style. Vlw @hkotsubo. Thank you so much for vdd

Browser other questions tagged

You are not signed in. Login or sign up in order to post.