javajava-8java-stream

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 ?


Solution

  • .filter(Objects::nonNull)
    

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

    Btw, you can do

    .map(callsBufferMap::get)