Monday , November 20 2017
Home / java8 / How to Filter null values from Java8 Stream

How to Filter null values from Java8 Stream

Here I am going to show you how to filter null values from Java8 Stream.

Java 8 Stream Example:


package com.onlinetutorialspoint.java8;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8_FilterNullValues_Stream {
    public static void main(String[] args) {
        Stream<String> deptList = Stream.of(new String("IT"), new String("HR"),
                null, new String("Development"), null,
                new String("Recruitment"));
        showData(deptList);
    }

    public static void showData(Stream<String> deptList) {
        List<String> result = deptList.collect(Collectors.toList());
        result.forEach(System.out::println);
    }
}

IT
HR
null
Development
null
Recruitment

On the above output, we can see that there are several null values. We can filter null values by below solution.

Filter null values :

We can filter the null values by applying the condition in filter(x != null) method.


package com.onlinetutorialspoint.java8;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8_FilterNullValues_Stream {
    public static void main(String[] args) {
        Stream<String> deptList = Stream.of(new String("IT"), new String("HR"),
                null, new String("Development"), null,
                new String("Recruitment"));
        removeNullObjets(deptList);
    }

    public static void removeNullObjets(Stream<String> deptList) {
        List<String> result = deptList.filter(x -> x != null).collect(
                Collectors.toList());
        result.forEach(System.out::println);
    }

}

IT
HR
Development
Recruitment

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

User defined sorting with Java 8 Comparator

In this tutorials, we are going to see how to sort user defined objects using …

Leave a Reply

Your email address will not be published. Required fields are marked *