Rodik
Rodik

Reputation: 271

How to avoid null values ​in a stream

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

Answers (3)

Harshal Khachane
Harshal Khachane

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

m0skit0
m0skit0

Reputation: 25874

Invert the condition: name.equals(e.getName())

.filter(e -> name.equals(e.getName()))

Upvotes: 2

Pawan Maurya
Pawan Maurya

Reputation: 397

You can check with the Optional.ofNullable(T) like this

  • check the value is not null
  • check with your string (list value and your desired string are equals or not )
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

Related Questions