Lambdaを使ったJava 8では、 Stream のヌル値はnullでない値をフィルタリングすることで削除できます。
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