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.