简体   繁体   中英

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?

.filter(Objects::nonNull)

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

Btw, you can do

.map(callsBufferMap::get)

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

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

Maybe you can do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM