Lambda가있는 Java 8에서는 null이 아닌 값을 필터링하여 Stream 의 null 값을 제거 할 수 있습니다.
stream.filter( a -> a != null )
이 예제는 먼저 2 개의 null 값을 갖는 Stream 을 생성합니다. Stream 은 먼저 null이 아닌 값으로 필터링됩니다. forEach 메서드를 사용하여 나머지 값이 출력에 기록됩니다. 출력에 null 값이 없음을 알 수 있습니다.
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