[Java 8 Examples] How to remove all Null values from List using Java 8 Lamdas



 Hi Guys,

Welcome to Java Inspires.

In this post, we will see how to remove all Null values from a Java List using Java 8 Lamdas.

package java8examples;

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

/**
 * 
 * @author #JavaInspires
 *
 */
public class Java8Example {

	public static void main(String[] args) {
		// create a string list
		List<String> names = new ArrayList<String>();
		// add elements
		names.add(null);
		names.add("John");
		names.add(null);
		names.add("David");
		names.add(null);
		// print names list with null values
		System.out.println(names);

		// remove null values
		names.removeIf(Objects::isNull);

		System.out.println(names);
	}
}

Output

[null, John, null, David, null]
[John, David]



About Objects class:

public final class Objects extends Object

This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.

public static boolean isNull(Object obj)

Returns true if the provided reference is null otherwise returns false.
API Note:
This method exists to be used as a Predicate, filter(Objects::isNull)
Parameters:
obj - a reference to be checked against null
Returns:
true if the provided reference is null otherwise false
Since:
1.8



Post a Comment

Previous Post Next Post