Reputation: 271
We are in the case where we have a corrupted data X in the list, and where the presence of this corrupted data X prevents an operation on Y data of the same type as X. . This isn't normal, and we must shield the code so that the presence of the corrupt data X does not block the use of other valid data.
I used Optional with an operation filter, for filter if the name is null we skip.
Personne personne = null;
String name= personne.getName();
try {
Optional<Personne> abstractPersonne=
APIPersonne.getAllPersonne(currentPersonne.getMethod())
.stream()
.filter(e -> e.getName() != null && e.getName().equals(name))
.findAny();
if (abstractPersonne.isPresent())
personne= abstractPersonne.get();
}
Is there a way to avoid the test of (e-> e.getName != null) ?
Upvotes: 0
Views: 160
Reputation: 266
Just reverse the condition, if you are sure that the variable "name" is null safe. For example instead of
e.getName().equals(name)
use
name.equals(e.getName())
Upvotes: 3
Reputation: 25874
Invert the condition: name.equals(e.getName())
.filter(e -> name.equals(e.getName()))
Upvotes: 2
Reputation: 397
You can check with the Optional.ofNullable(T) like this
Optional<Personne> abstractPersonne = APIPersonne
.getAllPersonne(currentPersonne.getMethod())
.stream()
.filter(e -> Optional.ofNullable(e).isPresent() && e.getName().equals(name))
.findAny();
if (abstractPersonne.isPresent())
personne= abstractPersonne.get();
Upvotes: 0