How to remove null values from array containing array

CodeHunter :

I have an array like this

String arr[][] = {{"abc"}, {"bcd"}, {null}}

This is multi dimensional array (single string array with in an array). I want to remove those nulls and want final result as {{"abc"}, {"bcd"}}. This array could be of any size and there can any number of nulls

I tried something like this. I know I can use traditional for loops, but I want to do it using java8 or more efficiently.

 String arr1[][] = Arrays.stream(arr)
            .filter(str -> (((str != null) && (str.length > 0))))
            .toArray(String[][]::new);
Andronicus :

You can use streaming from Arrays helper class an filter non-null values:

String arr[][] = {{"abc"}, {"bcd"}, {null}};

String result[][] = Arrays.stream(arr)
    .map(innerArray -> Arrays.stream(innerArray).filter(Objects::nonNull).toArray(String[]::new))
    .toArray(String[][]::new);

Edit:

As @Andreas pointed out, this leaves empty inner arrays, we need to filter them with additional filter(innerArray -> innerArray.length > 0). Finally:

String result[][] = Arrays.stream(arr)
    .map(innerArray -> Arrays.stream(innerArray).filter(Objects::nonNull).toArray(String[]::new))
    .filter(innerArray -> innerArray.length > 0)
    .toArray(String[][]::new);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141977&siteId=1