我有一个非常基本的问题,但显然找不到解决方案。我已经初始化了一个大小为100行100列的String数组。
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);
}
}