Question:
I'm trying to use this optional class to get the data with null, but it returns an error.
In the main class, I use for with this method. Profession and composition of people.
for(Pessoa p : pessoas) {
Optional<Profissao> temNome = p.profissao.getNomeP();
If used as a String
Optional<String> temNome =Optional.ofNullable(p.profissao.getNomeP());
works, but I didn't understand the difference
Answer:
Hi!
It seems to me, you're confusing. See, you're accessing the profession name, a string, and you're expecting 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 reading this article by Caelum . It gives a nice foundation. The documentation , although very complete, will not be very didactic Any doubts, 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 it in your person class, writing a getNameProfessional(), like this:
public class Pessoa{
...
public String getNomeProfissao(){
return Optional.ofNullable(this.profissao.getNomeP()).orElse("Nao tem Profissao");
}
...
}
This way you will follow the Law of Demeter, and you will not chain calls.