Filter/Remove null & empty string from array – lambda stream java8 (example)

  • Given an array of String Objects.
    • Array may also contain null and empty string object(s).
    • e.g Array can have elements like “[Soccer, Rugby, “”, Badminton, null, Golf, null, Tennis]”
  • We would like to remove or filter null or empty string elements from array.
  • We will using lambda stream to remove or filter empty elements /objects.

1. Remove/filter null & empty string objects from array-lambda stream java8

package org.learn;

import java.util.Arrays;

public class RemoveNullFromArray {

    public static void main(String[] args) {
        String[] stringArray = {
                "Soccer","Rugby","",
                "Badminton",null,"Golf",
                null,"Tennis"
        };
        System.out.println("1. Input Array containing empty string is: ");
        System.out.println(Arrays.toString(stringArray));
        System.out.println("2. Array after removing null and empty strings");

        String[] removedNull = Arrays.stream(stringArray)
                .filter(value ->
                        value != null && value.length() > 0
                )
                .toArray(size -> new String[size]);

        System.out.println(Arrays.toString(removedNull));
    }
}

Remove /filter null & empty string objects from array-lambda stream java8

1. Input Array containing empty string is: 
[Soccer, Rugby, , Badminton, null, Golf, null, Tennis]
2. Array after removing null and empty strings
[Soccer, Rugby, Badminton, Golf, Tennis]

 

Scroll to Top