Java 8 – Filter a null value from a Stream

Review a Stream containing null values.

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

Solution

To solve it, uses 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

Alternatively, filter with Objects::nonNull


import java.util.List;

	List<String> result = language.filter(Objects::nonNull).collect(Collectors.toList());

References

  1. Objects::nonNull JavaDoc
  2. Java 8 Streams filter examples
  3. Java 8 Collectors JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
5 Comment threads
0 Thread replies
3 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
satishFrederic LeitenbergerGerardopihentagyKiran U Recent comment authors
newest oldest most voted
Kiran U
Guest
Kiran U

It really helped me.. thank you so much

pihentagy
Guest
pihentagy

What about .filter(Objects::nonNull)

satish
Guest
satish

Objects::nonNull is recommended by Sonar

Frederic Leitenberger
Guest
Frederic Leitenberger

Is there a solution to this?

public void consume(@Nonnull string) {
// ...
}

public run() {
Steam<@Nullable String> stream = Stream.of("hello", null, "world");
stream.filter(Objects::nonNull).forEach(this::consume); // XXX this causes null-warnings because the filter-call does not change the nullness of the stream parameter
}

I have a solution using flatMap(), but it would be much nicer if the filter method could just return @Nonnull String when called using the Objects::nonNull function.

Gerardo
Guest
Gerardo

What if all elements are null? It will fail in the Collect or if I may have a mapping before collecting?