Site icon

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

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]

 

Exit mobile version