gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:36:17 27 4
gpt4 key购买 nike

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

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

但是大多数元素都是空的。我想删除那些空字符串但不使用不同的数组。假设非空字符串是从第 1 行到第 16 行,从第 1 列到第 10 列。所以最终的输出大小应该是

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

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

最佳答案

这是使用 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);
}

}

关于java - 删除空字符串并减少相同的 String[][] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53272862/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com