Can a list element be null?

Ranch Hand

Posts: 53

Ranch Hand

Posts: 1183

Marshal

Posts: 75053

Marshal

Posts: 22611

lavi mendonca

Ranch Hand

Posts: 53

Rob Spoor

Marshal

Posts: 22611

Campbell Ritchie

Marshal

Posts: 75053

Generally, no; there is no other way to tell that an arbitrary ArrayList contains ten instances of null than to loop over it and make sure each element is null . You can forgo this, of course, if the size() of the list isn't equal to ten.

Can we add NULL value in ArrayList in Java?

if you don't want to allow nulls to be added then you could wrap the array list with your own wrapper which threw when null was added. ArrayList allows null by design. It is intentional.

Can a list accept null?

Yes, you can always use null instead of an object. Just be careful because some methods might throw error. It would be 1. itemsList.

Can a list contains null?

An ArrayList element can be an object reference or the value null . When a cell contains null , the cell is not considered to be empty. The picture shows empty cells with an "X" and cells that contain a null with null . The cells that contain null are not empty, and contribute to the size of the list.

IS NULL allowed in ArrayList?

Storing nulls: In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number.

Does ArrayList accept null?

5) Nulls: ArrayList can have any number of null elements. HashMap allows one null key and any number of null values.

Can an ArrayList be empty?

No. An ArrayList can be empty (or with nulls as items) an not be null. It would be considered empty.

Can we add null elements to a set in Java?

As per the definition a set object does not allow duplicate values but it does allow at most one null value. Null values in HashSet − The HashSet object allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays only one null.

How to add nulls to an ArrayList in Java?

You can add nulls to the ArrayList, and you will have to check for nulls in the loop: itemsList.size(); would take the null into account. Output : Thank you, I am guessing the .size() method also takes the null values into account.

Why are null values allowed inside Java list stack overflow?

When you try to return, It returns null only. If you try to invoke methods/variables on that resulted null, then you run into NPE. Any use of list1 [0] will any way result into NPE . List maintains a list of object references.

Can a list have more than one null element?

More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals (e2), and they typically allow multiple null elements if they allow null elements at all. Some list implementations have restrictions on the elements that they may contain.


This seems to be more of a (software-)philosophic question here.

ArrayList as a utility class is designed to be helpful in a wide context of possible use-cases.

Contrary to your hidden claim that accepting null as a valid value should be discouraged, there are many examples where the null value is perfectly legal.

The single most important reason is that null is the do not know equivalent of any reference type, including framework types. This implies that null cannot be replaced in any case by a more fluent version of the nothing value.

So, lets say you store the Integers 1, 3, 7 in your arraylist at its corresponding index: Due to some computation, you want to get the element at index 5, so what your array should return is: "no value stored". This could be achieved through returning null or a NullObject. In most cases returning the built in null value is expressive enough. After calling a method that can return null and using its return value a check of the returned value against null is quite common in modern code.

This post will discuss how to remove nulls from a list in Java using plain Java, Guava library, and Apache Commons Collections.

List.remove(Object) removes the first occurrence of the specified object from the list. It returns true if the object is removed from the list and returns false if it is not present in the list.

To remove all null occurrences from the list, we can continuously call remove(null) until all null values are removed. Please note that the list will remain unchanged if it does not contain any null value.

import java.util.ArrayList;

    // Program to remove nulls from a list in Java

    public static void main(String[] args)

        List<String> colors = new ArrayList<>(

                Arrays.asList("RED", null, "BLUE", null, "GREEN"));

        // Plain Java – Using `List.remove()` method

        while (colors.remove(null)) {}

        System.out.println(colors);

Download  Run Code

Output:
[RED, BLUE, GREEN]

List.removeAll(Collection) removes elements contained in the specified collection from the list.

Unlike the remove() method, removeAll() will throw a NullPointerException if the specified collection is null. To remove all nulls occurrences from the list, we can pass a singleton list or set containing only null.

import java.util.ArrayList;

import java.util.Collections;

    // Program to remove nulls from a list in Java

    public static void main(String[] args)

        List<String> colors = new ArrayList<>(

                Arrays.asList("RED", null, "BLUE", null, "GREEN"));

        colors.removeAll(Collections.singletonList(null));

        System.out.println(colors);

Download  Run Code

Output:
[RED, BLUE, GREEN]

3. Using Iterator

The idea is very simple – loop through the list using an iterator and remove all null elements from it.

import java.util.ArrayList;

import java.util.Iterator;

    // Generic method to remove nulls from a list in Java

    public static<T> void removeNulls(List<T> list)

        Iterator<T> itr = list.iterator();

                itr.remove();    // remove nulls

    // Program to remove all null values from a list in Java

    public static void main(String[] args)

        List<String> colors = new ArrayList<>(

                Arrays.asList("RED", null, "BLUE", null, "GREEN"));

        System.out.println(colors);

Download  Run Code

Output:
[RED, BLUE, GREEN]

4. Using Guava Library

Guava’s Iterables class provides removeIf(Iterable, Predicate) that removes every element from a specified iterable that satisfies the provided predicate.

import com.google.common.base.Predicates;

import com.google.common.collect.Iterables;

import java.util.ArrayList;

    // Program to remove nulls from a list in Java using Guava

    public static void main(String[] args)

        List<String> colors = new ArrayList<>(

                Arrays.asList("RED", null, "BLUE", null, "GREEN"));

        Iterables.removeIf(colors, Predicates.isNull());

        System.out.println(colors);

Download Code

Output:
[RED, BLUE, GREEN]

 
We can also use lambda expressions in Java 8 and above:

Iterables.removeIf(colors, x -> x == null);

5. Using Apache Commons Collections

Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that can filter the collection by applying specified Predicate to each element. If the predicate returns false, it removes the element.

import org.apache.commons.collections4.CollectionUtils;

import org.apache.commons.collections4.PredicateUtils;

import java.util.ArrayList;

    // Program to remove nulls from a list using Apache Commons Collections

    public static void main(String[] args)

        List<String> colors = new ArrayList<>(

                Arrays.asList("RED", null, "BLUE", null, "GREEN"));

        // Using Apache Commons Collections

        CollectionUtils.filter(colors, PredicateUtils.notNullPredicate());

        System.out.println(colors);

Download Code

Output:
[RED, BLUE, GREEN]

 
We can also use lambda expressions in Java 8 and above:

CollectionUtils.filter(colors, x -> x != null);

 
Apache Commons Collections also provides the filterInverse(Iterable, Predicate) that works similarly, except it removes the element if the predicate returns true.

CollectionUtils.filterInverse(colors, PredicateUtils.nullPredicate());

CollectionUtils.filterInverse(colors, x -> x == null);

That’s all about removing nulls from a List in Java.

 
Suggested Read:

Remove null values from a List in Java 8 and above


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


Video liên quan

Chủ đề