7

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 ?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
harp1814
  • 1,494
  • 3
  • 13
  • 31
  • 2
    Alternate to `.filter(Objects::nonNull)` is `Collectors.filtering(Objects::nonNull, Collectors.toList()`. It depends on your taste. – Aniket Sahrawat Sep 21 '20 at 11:18

4 Answers4

13
.filter(Objects::nonNull)

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

Btw, you can do

.map(callsBufferMap::get)
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • 2
    Or with Java 9+: `List updatedList = updatingUniquedList .stream() .flatMap(s -> Stream.ofNullable(callsBufferMap.get(s))) .collect(Collectors.toList());` – Holger Sep 21 '20 at 11:49
4

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

Stefan Zhelyazkov
  • 2,599
  • 4
  • 16
  • 41
3

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());
flaxel
  • 4,173
  • 4
  • 17
  • 30
2

Maybe you can do something like this:

Collectors.filtering(Objects::nonNull, Collectors.toList())
Sobhan
  • 1,280
  • 1
  • 18
  • 31