提问人:harp1814 提问时间:9/21/2020 最后编辑:Andrew Tobilkoharp1814 更新时间:9/21/2020 访问量:11370
Java Stream:如何避免在 Collectors.toList() 中添加 null 值?
Java Stream: How to avoid add null value in Collectors.toList()?
问:
有一些 Java 代码:
List<Call> updatedList = updatingUniquedList
.stream()
.map(s -> {
Call call = callsBufferMap.get(s);
}
return call;
}).collect(Collectors.toList());
如果调用变量为空,如何避免避免添加到最终列表?
答:
4赞
Stefan Zhelyazkov
9/21/2020
#1
您可以使用 after 和 before 。.filter(o -> o != null)
map
collect
13赞
Andrew Tobilko
9/21/2020
#2
.filter(Objects::nonNull)
在收集之前。或者用 if 将其重写为简单的 foreach。
顺便说一句,你可以做到
.map(callsBufferMap::get)
评论
2赞
Holger
9/21/2020
或者使用 Java 9+:List<Call> updatedList = updatingUniquedList .stream() .flatMap(s -> Stream.ofNullable(callsBufferMap.get(s))) .collect(Collectors.toList());
3赞
flaxel
9/21/2020
#3
您可以使用以下几个选项:
- 在 Stream 中使用 Nonnull 方法:
.filter(Objects::nonNull)
- 使用 removeIf of list:
updatedList.removeIf(Objects::isNull);
例如,这些行可以如下所示:
List<Call> updatedList = updatingUniquedList
.stream()
.map(callsBufferMap::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
2赞
Sobhan
9/21/2020
#4
也许你可以做这样的事情:
Collectors.filtering(Objects::nonNull, Collectors.toList())
评论
.filter(Objects::nonNull)
Collectors.filtering(Objects::nonNull, Collectors.toList()