Java Stream: How to avoid add null value in Collectors.toList()?

13k views Asked by At

There is some Java code:

 List<Call> updatedList = updatingUniquedList 
      .stream()
      .map(s -> {
       Call call = callsBufferMap.get(s);
      }
        return call;
     }).collect(Collectors.toList());

How to avoid avoid to add to final list if call variable is null ?

4

There are 4 answers

1
Andrew Tobilko On BEST ANSWER
.filter(Objects::nonNull)

before collecting. Or rewrite it to a simple foreach with an if.

Btw, you can do

.map(callsBufferMap::get)
0
Stefan Zhelyazkov On

You can use .filter(o -> o != null) after map and before collect.

0
flaxel On

There are several options you can use:

  1. using nonnull method in stream: .filter(Objects::nonNull)
  2. using removeIf of list: updatedList.removeIf(Objects::isNull);

So for example the lines can look like this:

 List<Call> updatedList = updatingUniquedList
     .stream()
     .map(callsBufferMap::get)
     .filter(Objects::nonNull)
     .collect(Collectors.toList());
0
Sobhan On

Maybe you can do something like this:

Collectors.filtering(Objects::nonNull, Collectors.toList())