如何在Java中移除多维字符串数组中的空元素

问题描述 投票:-1回答:2
String[][] array= {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};

我想从数组中删除{"",""}这些元素

如何在Java中完成?请帮忙 !!!

java arrays string arraylist multidimensional-array
2个回答
0
投票
private String[][] removeFromArray(String[][] source, String[] objToRemove) {
    return Arrays.stream(source)
                 .filter(a -> !Arrays.equals(a, objToRemove))
                 .toArray(String[][]::new);
}

void example() {
    final String[] empty = new String[]{"", ""};
    String[][] array = {{"abcd", ""}, {"asdf", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}};
    array = removeFromArray(array, empty);
}

-1
投票

删除?您不能更改现有阵列的大小。如果要创建仅包含这些元素的新数组,请计算每个数组的长度,根据这些长度创建一个新数组,然后将元素添加到新数组中。

String[][] array= {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
//Assuming you want a 1-D array
int valuesPresent = 0;
for (int i = 0; i < arrray.length; i++) {
    for (int j = 0; i < arrray[i].length; i++) {
        if (array[i][j] != "") {
            valuesPresent++;
        }
    }
}
//Now you know how many values are there, so initialize a new array of that size 
String[] answer = new String[valuesPresent];
//Now add all the values to it
int index = 0;
for (int i = 0; i < arrray.length; i++) {
    for (int j = 0; i < arrray[i].length; i++) {
        if (array[i][j] != "") {
            answer[index] = array[i][j];
            index++;
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.