Doubt with the use of the Optional

3

I'm trying to use this optional class to get the data with null, but it returns error.

In the main class, I use the for with this method. Profession and composition of people.

for(Pessoa p : pessoas) {

        Optional<Profissao> temNome = p.profissao.getNomeP();

If used as String

Optional<String> temNome =Optional.ofNullable(p.profissao.getNomeP());

It works, but I did not understand the difference.

    
asked by anonymous 18.11.2016 / 14:21

2 answers

2

Hello

As it seems to me, you are confusing. See, you are accessing the name of the profession, a string, and are waiting for it to return the parent object, profession.

for(Pessoa p : pessoas) {
   Optional<Profissao> temNome = p.profissao.getNomeP();
   ...
}

The right thing here would be:

for(Pessoa p : pessoas) {
   Optional<Profissao> possivelProfissao = Optional.ofNullable(p.profissao);
   possivelProfissao.ifPresent( profissao -> System.out.println(p.getNomeP()) );
   ...
}

Or:

for(Pessoa p : pessoas) {
   Optional<Profissao> possivelProfissao = Optional.ofNullable(p.profissao);
   if(possivelProfissao.isPresent()){
      String nome = possivelProfissao.get().getNomeP();
      System.out.println(nome );
   }
   ...
}

I recommend a read in this Caelum article. >. It gives a legal basis. The documentation , although complete, will not be there for you. Any questions, just ask.

Issue 01

If you want to return a default String when there is no profession, you can do something like this:

public String temNome(Profissao profissao) {
  return Optional.ofNullable(profissao.getNomeP()).orElse("Nao tem Profissao");
}

The cool thing is that you do in your person class by writing a getNomeProfession (), like this:

public class Pessoa{
   ...
   public String getNomeProfissao(){
      return Optional.ofNullable(this.profissao.getNomeP()).orElse("Nao tem Profissao");
   }
   ...
}

So you will follow Demeter's Law, and will not chain calls.

    
18.11.2016 / 15:47
0

I created a method, I believe it is correct

public  String temNome(Profissao profissao) {

        Optional<String> nomeProfissao = Optional.ofNullable(profissao.getNomeP());

        if(nomeProfissao.isPresent()) {

            return profissao.getNomeP();
        }  

        return "Nao tem Profissao";

    }
    
18.11.2016 / 16:48