引言
本文展示如何过滤一个空值的流对象。
检查包含空值的流。
public static void main(String[] args) {
Stream language = Stream.of("java", "python", "node", null, "ruby", null, "php");
List result = language.collect(Collectors.toList());
result.forEach(System.out::println);
}
输出:
java
python
node
null //
ruby
null //
php
使用 Stream.filter (x-x! null)
public static void main(String[] args) {
Stream language = Stream.of("java", "python", "node", null, "ruby", null, "php");
//List result = language.collect(Collectors.toList());
List result = language.filter(x -> x!=null).collect(Collectors.toList());
// 或使用 Objects: : nonNull 进行筛选
List result = language.filter(Objects::nonNull).collect(Collectors.toList());
result.forEach(System.out::println);
}
输出:
java
python
node
ruby
php