Java how to remove null values collections

Java how to remove null values collections

To remove null values from a collection in Java, you can use the removeIf method of the Collection interface, which is implemented by various collection classes such as List, Set, and Queue. The removeIf method removes all elements from the collection that match a specified predicate.

Here is an example of how you can use the removeIf method to remove null values from a List collection in Java:

refer to:‮ruttual‬i.com
import java.util.ArrayList;
import java.util.List;

List<String> list = new ArrayList<>(List.of("Hello", null, "World", null));
list.removeIf(e -> e == null);

System.out.println(list);  // Outputs "[Hello, World]"

In this example, the removeIf method is called on the listList object, and it removes all elements that are equal to null (i.e., e == null).

You can use similar logic to remove null values from other collection types, such as Set or Queue, by calling the removeIf method on the collection object and specifying a predicate that matches null values.

Keep in mind that the removeIf method operates on the original collection and removes elements in-place, without creating a new collection. If you want to create a new collection with null values removed, you can use the stream API or the filter method of the Stream interface to filter out null values, and then use the collect method to create a new collection.

For example:

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

List<String> list = new ArrayList<>(List.of("Hello", null, "World", null));
List<String> nonNullList = list.stream().filter(e -> e != null).collect(Collectors.toList());

System.out.println(nonNullList);  // Outputs "[Hello, World]"
Created Time:2017-11-03 23:27:11  Author:lautturi