How should we manage jdk8 stream for null values

前端 未结 5 1336
北海茫月
北海茫月 2020-12-04 10:53

Hello fellow Java developers,

I know the subject may be a bit in advance as the JDK8 is not yet released (and not for now anyway..) but I was reading som

5条回答
  •  臣服心动
    2020-12-04 11:41

    If you just want to filter null values out of a stream, you can simply use a method reference to java.util.Objects.nonNull(Object). From its documentation:

    This method exists to be used as a Predicate, filter(Objects::nonNull)

    For example:

    List list = Arrays.asList( null, "Foo", null, "Bar", null, null);
    
    list.stream()
        .filter( Objects::nonNull )  // <-- Filter out null values
        .forEach( System.out::println );
    

    This will print:

    Foo
    Bar
    

提交回复
热议问题