Filter/remove null element/String from arraylist of objects – lambda stream java8 (example)

  1. Given an ArrayList collection containing String Objects in java.
    • List<String> stringList = new ArrayList<String>();
  2. ArrayList collection will contain null elements also.
    • [Soccer, Rugby, null, Badminton, null, Golf, null, Tennis]
  3. We would like to remove null elements/String objects from List of objects.
  4. We will use filter feature of lambda stream in Java8.

1. Filter/remove null elements from arraylist of objects – lambda stream

package org.learn.org.learn.files;

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

public class RemoveNullsFromList {

    public static void main(String[] args) {

        List<String> stringList = new ArrayList<>();
        stringList.add("Soccer");
        stringList.add("Rugby");
        stringList.add(null);
        stringList.add("Badminton");
        stringList.add(null);
        stringList.add("Golf");
        stringList.add(null);
        stringList.add("Tennis");

        System.out.println("1. Given ArrayList containing null string objects");
        System.out.println(stringList);

        System.out.println("2. Removed null string objects from ArrayList collection");
        List<String> removedNulls = stringList
                .stream()
                .filter(
                        value -> value != null
                )
                .collect(Collectors.toList());
        System.out.println(removedNulls);
    }
}

2. Output – remove null Strings from list of objects (lambda stream java 8)

1. Given ArrayList containing null string objects
[Soccer, Rugby, null, Badminton, null, Golf, null, Tennis]
2. Removed null string objects from ArrayList collection
[Soccer, Rugby, Badminton, Golf, Tennis]
Scroll to Top