Hello!
As far as I’m concerned, you’re confusing it.
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();
...
}
Right 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 on this article from Caelum. It provides a legal basis.
To documentation, although well completed, there will be no didactic mto
Any questions, just ask.
Edition 01
If you want to return a standard 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 coolest thing is that you do in your person class, writing a getNomeProfissao(), 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.
If you do so
p.profissao.ifPresent(prof -> System.out.println(prof.getNomeP()));
shows the name?– Sorack
The ifPresent option does not appear, Voce meant ? temNome.ifPresent() { }
– user60896
Actually I understood your doubt now. Your second option works because you are calling last the
getNomeP
that returns aString
and not a profession– Sorack