在带有Lambda的Java 8中,可以通过对非空值进行筛选来删除来自 Stream 的空值。
stream.filter( a -> a != null )
这个例子首先创建一个带有2个空值的 Stream 。 首先对 Stream 进行过滤,使其不为空; 然后使用forEach方法将剩余的值写入输出中。 您可以看到输出没有任何空值。
import java.util.stream.Stream;
public class LambdaStreamFilterNull {
public static void main(String[] argv){
// Create an String with null values
Stream<String> stream = Stream.of( "a", null, "c", null, "a", "b", "b");
System.out.println( "Stream without null values:" );
// Filter the stream
stream.filter( a -> a != null )
.forEach( o -> System.out.println( o ) );
}
}
Stream without null values: a c a b b