Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaJava program to remove nulls from a List Container

Java program to remove nulls from a List Container

List is an ordered collection of objects which allows to store duplicate values or null values, in the insertion order. So it is very important to remove null values in many scenarios.

Examples:

Input:  [Geeks, null, forGeeks, null, A computer portal]
Output: [Geeks, forGeeks, A computer portal]

Input:  [1, null, 2, 3, null, 4]
Output: [1, 2, 3, 4]

Below are the methods to remove nulls from a List in Java:

  1. Using List.remove() List interface provides a pre-defined method remove(element) which is used to remove a single occurrence of the element passed, from the List, if found.

    Algorithm:

    1. Get the list with null values.
    2. Repeatedly call remove(null) on the list, until all null values are removed.
    3. Return/Print the list (now with all null values removed).




    // Java Program to remove nulls
    // from a List using List.remove()
      
    import java.util.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Create the list with null values
            List<String> list = new ArrayList<>(
                Arrays.asList("Geeks",
                              null,
                              "forGeeks",
                              null,
                              "A computer portal"));
      
            // Print the list
            System.out.println("Initial List: " + list);
      
            // Removing nulls using List.remove()
            // Repeatedly call remove() till all null are removed
            while (list.remove(null)) {
            }
      
            // Print the list
            System.out.println("Modified List: " + list);
        }
    }

    
    
    Output:

    Initial List: [Geeks, null, forGeeks, null, A computer portal]
    Modified List: [Geeks, forGeeks, A computer portal]
    
  2. Using List.removeAll(): List interface provides another pre-defined method removeAll(Collection) which is used to remove all occurrences of the elements of the Collection passed, from the List, if found.

    Algorithm:

    1. Get the list with null values.
    2. Create a Collection with only null as element using Collections.singletonList(null)
    3. Call removeAll(Collection) on the list once.
    4. Return/Print the list (now with all null values removed).




    // Java Program to remove nulls
    // from a List using List.removeAll()
      
    import java.util.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Create the list with null values
            List<String> list = new ArrayList<>(
                Arrays.asList("Geeks",
                              null,
                              "forGeeks",
                              null,
                              "A computer portal"));
      
            // Print the list
            System.out.println("Initial List: " + list);
      
            // Removing nulls using List.removeAll()
            // passing a collection with single element "null"
            list.removeAll(Collections.singletonList(null));
      
            // Print the list
            System.out.println("Modified List: " + list);
        }
    }

    
    
    Output:

    Initial List: [Geeks, null, forGeeks, null, A computer portal]
    Modified List: [Geeks, forGeeks, A computer portal]
    
  3. Using iterator: Iterator is an interface which belongs to collection framework. It allows user to traverse the collection, access the data element and remove the data elements of the collection.

    Algorithm:

    1. Get the list with null values.
    2. Create an iterator from the list
    3. Traverse through each element of the List with the of created Iterator
    4. Check, for each element, if it is null. If found null, call IteratorElement.remove() on that element.
    5. Return/Print the list (now with all null values removed).

    Program:




    // Java Program to remove nulls
    // from a List using iterator
      
    import java.util.*;
      
    class GFG {
      
        // Generic function to remove Null Using Iterator
        public static <T> List<T> removeNullUsingIterator(List<T> list)
        {
      
            // Create an iterator from the list
            Iterator<T> itr = list.iterator();
      
            // Find and remove all null
            while (itr.hasNext()) {
                if (itr.next() == null)
                    itr.remove(); // remove nulls
            }
      
            // Return the null
            return list;
        }
      
        public static void main(String[] args)
        {
      
            // Create the list with null values
            List<String> list = new ArrayList<>(
                Arrays.asList("Geeks",
                              null,
                              "forGeeks",
                              null,
                              "A computer portal"));
      
            // Print the list
            System.out.println("Initial List: " + list);
      
            // Removing nulls using iterator
            list = removeNullUsingIterator(list);
      
            // Print the list
            System.out.println("Modified List:  " + list);
        }
    }

    
    
    Output:

    Initial List: [Geeks, null, forGeeks, null, A computer portal]
    Modified List:  [Geeks, forGeeks, A computer portal]
    
  4. Using Guava Iterables removeIf(): Guava Iterables class provides Iterables.removeIf(Iterable, Predicate) that removes every element from a specified Iterable (or Collections that implements Iterable) that satisfies the provided predicate.

    Algorithm:

    1. Get the list with null values.
    2. Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()
    3. Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.
    4. Return/Print the list (now with all null values removed).




    // Java Program to remove nulls
    // from a List using Guava Iterables
      
    import com.google.common.base.Predicates;
    import com.google.common.collect.Iterables;
    import java.util.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Create the list with null values
            List<String> list = new ArrayList<>(
                Arrays.asList("Geeks",
                              null,
                              "forGeeks",
                              null,
                              "A computer portal"));
      
            // Print the list
            System.out.println("Initial List: " + list);
      
            // Removing nulls using Guava Iterables
            // using Predicate condition isNull()
            Iterables.removeIf(list, Predicates.isNull());
      
            // Print the list
            System.out.println("Modified List: " + list);
        }
    }

    
    
    Output:

    Initial List: [Geeks, null, forGeeks, null, A computer portal]
    Modified List: [Geeks, forGeeks, A computer portal]
    
  5. Using Apache Commons Collections filter(): Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that removes every element from a specified iterable that do not satisfies the provided predicate.

    Algorithm:

    1. Get the list with null values.
    2. Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.
    3. Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.
    4. Return/Print the list (now with all null values removed).

    Program:




    // Java Program to remove nulls
    // from a List using Apache Common COllection Filter()
    import org.apache.commons.collections4.CollectionUtils;
    import org.apache.commons.collections4.PredicateUtils;
    import java.util.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Create the list with null values
            List<String> list = new ArrayList<>(
                Arrays.asList("Geeks",
                              null,
                              "forGeeks",
                              null,
                              "A computer portal"));
      
            // Print the list
            System.out.println("Initial List: " + list);
      
            // Removing nulls using Apache Common filter()
            // using Predicate condition notNullPredicate()
            CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
      
            // Print the list
            System.out.println("Modified List: " + list);
        }
    }

    
    
    Output:

    Initial List: [Geeks, null, forGeeks, null, A computer portal]
    Modified List: [Geeks, forGeeks, A computer portal]
    
  6. Using Lambdas (Java 8): Stream.filter() method can be used in Java 8 that returns a stream consisting of the elements
    that match the given predicate condition.

    Algorithm:

    1. Get the list with null values.
    2. Create a Stream from the list using list.stream()
    3. Filter the stream of elements that are not null using list.filter(x -> x != null)
    4. Collect back the Stream as List using .collect(Collectors.toList()
    5. Return/Print the list (now with all null values removed).




    // Java Program to remove nulls
    // from a List using Apache Common COllection Filter()
      
    import java.util.stream.Collectors;
    import java.util.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Create the list with null values
            List<String> list = new ArrayList<>(
                Arrays.asList("Geeks",
                              null,
                              "forGeeks",
                              null,
                              "A computer portal"));
      
            // Print the list
            System.out.println("Initial List: " + list);
      
            // Removing nulls using Java Stream
            // using Predicate condition in lambda expression
            list = list.stream()
                       .filter(x -> x != null)
                       .collect(Collectors.toList());
      
            // Print the list
            System.out.println("Modified List: " + list);
        }
    }

    
    
    Output:

    Initial List: [Geeks, null, forGeeks, null, A computer portal]
    Modified List: [Geeks, forGeeks, A computer portal]
    
RELATED ARTICLES

Most Popular

Recent Comments