Java流(Java Stream):如何避免在Collectors.toList()中添加空值?

huangapple go评论64阅读模式
英文:

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

问题

有一些Java代码:

List<Call> updatedList = updatingUniquedList 
     .stream()
     .map(s -> {
         Call call = callsBufferMap.get(s);
         if (call != null) {
             return call;
         } else {
             // Do something if call variable is null
             return null;  // or any desired value
         }
     }).collect(Collectors.toList());

如何避免在call变量为null时将其添加到最终列表中?

英文:

There is some Java code:

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

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

答案1

得分: 13

.filter(Objects::nonNull)
在收集之前使用过滤。或者将其重写为一个带有条件语句的简单 foreach。

顺便说一下,你可以这样做

.map(callsBufferMap::get)
英文:
.filter(Objects::nonNull)

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

Btw, you can do

.map(callsBufferMap::get)

答案2

得分: 4

你可以在 map 之后、collect 之前使用 .filter(o -> o != null)

英文:

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

答案3

得分: 3

有几个选项可供您使用:

  1. 在流中使用nonnull方法:.filter(Objects::nonNull)
  2. 使用列表的removeIf方法:updatedList.removeIf(Objects::isNull);

所以例如这些行可以看起来像这样:

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

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&lt;Call&gt; updatedList = updatingUniquedList
     .stream()
     .map(callsBufferMap::get)
     .filter(Objects::nonNull)
     .collect(Collectors.toList());

答案4

得分: 2

也许你可以尝试类似这样的操作:

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

Maybe you can do something like this:

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

huangapple
  • 本文由 发表于 2020年9月21日 19:12:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63991118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定