简体   繁体   English

如何从包含数组的数组中删除空值

[英]How to remove null values from array containing array

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"}} .我想删除这些空值并希望最终结果为{{"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.我知道我可以使用传统的 for 循环,但我想使用 java8 或更有效地做到这一点。

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

You can use streaming from Arrays helper class an filter non-null values:您可以使用来自Arrays助手类的流过滤器非空值:

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) .正如@Andreas 指出的那样,这会留下空的内部数组,我们需要使用额外的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);

you're almost there with your solution;你的解决方案就快到了; just one mistake with a check:支票只有一个错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM