让我们看看一个包含null
值的Stream
Java8Examples.java
package com.mkyong.java8;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8Examples {
public static void main(String[] args) {
Stream<string> language = Stream.of("java", "python", "node", null, "ruby", null, "php");
List<string> result = language.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
output
java
python
node
null // <--- NULL
ruby
null // <--- NULL
php
解决方法
可以使用Stream.filter(x -> x!=null)
的方法解决。
Java8Examples.java
package com.mkyong.java8;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8Examples {
public static void main(String[] args) {
Stream<string> language = Stream.of("java", "python", "node", null, "ruby", null, "php");
//List<string> result = language.collect(Collectors.toList());
List<string> result = language.filter(x -> x!=null).collect(Collectors.toList());
result.forEach(System.out::println);
}
}
output
java
python
node
ruby
php
也可以用Objects::nonNull
方法来替代。
import java.util.List;
List<string> result = language.filter(Objects::nonNull).collect(Collectors.toList());
References
- Objects::nonNull JavaDoc
- Java 8 Streams filter examples
- [Java 8 Collectors JavaDoc][]
[Java 8 Collectors JavaDoc]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html