harp1814
harp1814

Reputation: 1658

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

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 ?

Upvotes: 9

Views: 15892

Answers (4)

Sobhan
Sobhan

Reputation: 1460

Maybe you can do something like this:

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

Upvotes: 2

flaxel
flaxel

Reputation: 4607

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());

Upvotes: 4

Andrew
Andrew

Reputation: 49656

.filter(Objects::nonNull)

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

Btw, you can do

.map(callsBufferMap::get)

Upvotes: 14

Stefan Zhelyazkov
Stefan Zhelyazkov

Reputation: 2981

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

Upvotes: 4

Related Questions