Java 8 - How to filter null objects

Most of the time, we require to remove null objects from collection. I have seen people looping collection and retrieving the non-null objects.

Java 8 onwards we can remove null objects from collection with the help of stream as shown below - 

Approach 1

We can use Stream.filter(x -> x!=null) to filter null objects from collection as shown below - 

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

public class DemoStream {
	public static void main(String[] args) {
		List lst = new ArrayList<>();
		lst.add("Java");
		lst.add("J2EE");
		lst.add(null);
		lst.add("Spring");
		
		System.out.println("Before removing null values : "+lst);
		//Using Stream.filter(x -> x!=null)
		List lst1 = lst.stream().filter(x -> x != null).collect(Collectors.toList());
		System.out.println("After removing null values : "+lst1);
	}
}

Output

Before removing null values : [Java, J2EE, null, Spring]
After removing null values : [Java, J2EE, Spring]

This

remove null values

Approach 2

Another approach to remove null values from collection is using fitlter with Objects::nonNull as shown below - 

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

public class DemoStream {
	public static void main(String[] args) {
		List lst = new ArrayList<>();
		lst.add("Java");
		lst.add("J2EE");
		lst.add(null);
		lst.add("Spring");
		
		System.out.println("Before removing null values : "+lst);
		//Using Objects::nonNull
		List lst1 = lst.stream().filter(Objects::nonNull).collect(Collectors.toList());
		System.out.println("After removing null values : "+lst1);
	}
}

Output

remove null values using Objects:notnull

Approach 3

We can remove null objects from collection using removeIf() method and pass x->x ==null as predicate. 

import java.util.ArrayList;
import java.util.List;

public class DemoStream {
	public static void main(String[] args) {
		List lst = new ArrayList<>();
		lst.add("Java");
		lst.add("J2EE");
		lst.add(null);
		lst.add("Spring");
		
		System.out.println("Before removing null values : "+lst);
		//Using removeIf
		lst.removeIf(x -> x == null);
		System.out.println("After removing null values : "+lst);
	}
}

Output

removeIf method

In this article we learnt how to remove null objects from collection in Java 8.

Article tagged as
Author
Author: Amit Gupta
Published On: 27/02/2018
Last revised On: 27/02/2018
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media