删除空字符串并减少相同的String [] []数组

时间:2018-11-13 02:23:14

标签: java arrays string multidimensional-array

我有一个非常基本的问题,但显然找不到解决方案。我已经初始化了一个大小为100行100列的String数组。

String[][] array1 = new String[100][100];

但是大多数元素都是空的。我想删除那些空字符串,但不使用其他数组。假设非空字符串来自第1到16行以及第1到10列,因此最终输出大小应为

String[][] array1 = new String [16][10];

如何从第一个数组中查找和删除字符串,并同时减小数组的大小?

5 个答案:

答案 0 :(得分:1)

这是使用Streams的一种巧妙方法

array = (String[][]) Arrays.asList(array).stream()
                            // Filters out empty arrays
                            .filter(checkEmptyArrays())
                            // Filters out empty strings
                            .map(x -> cleanUpEmptyStrings(x))
                            // Collects it all back into the array matrix
                            .collect(Collectors.toList()).toArray(new String[0][0]);


private String[] cleanUpEmptyStrings(String[] x) {
    return Arrays.asList(x).stream().filter(y -> y != null && !y.equals("")).collect(Collectors.toList()).toArray(new String[0]);
}

private Predicate<String[]> checkEmptyArrays() {
    return k -> Arrays.stream(k).filter(l -> l != null && !l.equals("")).count() != 0;
}

这是测试

@Test
public void test() {
    String[][] array = new String[100][100];
    for (int i=0;i< 10; i++) {
        for (int j=10; j< 16; j++) {
            array[i][j] = "abcd";
        }
    }

    array = (String[][]) Arrays.asList(array).stream()
                            // Filters out empty arrays
                            .filter(checkEmptyArrays())
                            // Filters out empty strings
                            .map(x -> cleanUpEmptyStrings(x))
                            // Collects it all back into the array matrix
                            .collect(Collectors.toList()).toArray(new String[0][0]);

    for (String[] a: array) {
        System.out.println(a.length);
    }

}

答案 1 :(得分:0)

无法更改数组的大小。但是,您可以通过重新分配变量来做到这一点:

int x, y = size that you have determined the final array should be
String[][] temp = new String[x][y]
//Copy the values that are not empty into temp
array1 = temp

这将用适当大小的版本替换array1,而不必引入另一个永久变量(此后可以忽略x,y和temp)

答案 2 :(得分:0)

您无法减小数组的大小。但是,您可以创建一个返回旧数组的修剪版本的方法,例如

static String[][] trimArr( String[][] oldArr, int rows, int cols)
{
    String[][] trimmedArr = new String[rows][cols];
    for (int i = 0; i < trimmedArr.length; i++)
         for (int j = 0; j < trimmedArr[i].length; j++)
             trimmedArr[i][j] = oldArr[i][j];            
    return trimmedArr;
}

答案 3 :(得分:0)

数组具有固定长度。您必须将其替换为另一个符合您要求的阵列

答案 4 :(得分:0)

正如其他答案和评论所建议的那样,您不能更改数组的大小,而必须创建一个新数组。
但是,最好使用Collection,它将自动调整其大小。

如果您仍然想使用新数组来执行此操作,请按以下步骤操作:-
我采用了3x3的数组,您可以将代码用于100x100

{"row0 col0", "", "row0 col2"},
{"row1 col0", "", ""},
{"", "", ""}

在此示例中,由于任何行使用的最大列数为2,我们可以使新数组只有2列而不是3列。

类似地,最后一行实际上是空的,没有非空字符串,我们可以使新数组只有2行而不是3行。

public static void main(String[] args) {
    String[][] array1 = new String[][]{
            {"row0 col0", "", "row0 col2"},
            {"row1 col0", "", ""},
            {"", "", ""}
    };

    long maxNoOfColumnsInAnyRow = Arrays.stream(array1)
            .map(strings -> Arrays.stream(strings)
                    .filter(s -> s != null && !s.isEmpty())
                    .count())
            .max(Long::compareTo)
            .orElse((long) array1[0].length);

    long noOfNonEmptyRows = Arrays.stream(array1)
            .filter(strings -> Arrays.stream(strings)
                    .anyMatch(s -> s != null && !s.isEmpty()))
            .count();

    String[][] array2 = new String[(int) noOfNonEmptyRows][(int) maxNoOfColumnsInAnyRow];

    int i = 0, j;
    for (String[] strings : array1) {
        j = 0;
        for (String str : strings) {
            if (str != null && !str.isEmpty()) {
                array2[i][j] = str;
                j++;
            }
        }
        if (j != 0) i++;
    }

    System.out.println(Arrays.deepToString(array2));
}

输出为[[row0 col0, row0 col2], [row1 col0, null]],它是一个2x2的数组。