【发布时间】:2020-08-09 17:33:28
【问题描述】:
String[][] array = {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
我想从数组中删除 {"",""} 元素。
如何在 Java 中做到这一点?
【问题讨论】:
标签: java arrays string multidimensional-array filtering
String[][] array = {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
我想从数组中删除 {"",""} 元素。
如何在 Java 中做到这一点?
【问题讨论】:
标签: java arrays string multidimensional-array filtering
删除?
您无法更改现有数组的大小。
如果你想创建一个只有这些元素的新数组,计算每个数组的长度,根据这些长度创建一个新数组,将元素添加到新数组中。
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++;
}
}
}
获取二维数组,简单易懂:
//Just reordered input so we can understand better
String[][] array= {{"abcd","zxcs"}, //Row 0, col 0 = abcd and col 1 = zxcs
{"asdf",""}, //Row 1, col 0 = asdf and col 1 = ""
{"",""}}; //Row 2, col 0 = "" and col 2 = ""
//Counts how many columns have values(are not equal to "") in each row
int rowsWithValues = 0; //Counts how many rows have at least 1 value. Here, 2
for (int row = 0; row < arrray.length; row++) {
for (int col = 0; col < arrray[row].length; col++) {
if (array[row][col] != "") {
rowsWithValues++; //Since there's a col with value for this row
break; //If any one value has been found, no need to check other cols
}
}
}
//Now we know how many rows we need in the result array: 2 (row 2 has no values)
String[][] result = new String[2][];
//We need to add the 2 rows with values now
int arrayIndex = 0; //Points to next empty index in result[][]
for (int row = 0; row < arrray.length; row++) {
int colsWithValues = 0; //Cols with values for each row
for (int col = 0; col < arrray[i].length; col++) {
if (array[row][col] != "") {
colsWithValues ++; //Col with value found for this row
}
}
//Eg. For row 0, colsWithValues will be 2, since 2 cols have values(abcd, zxcs)
//We need to add these 2 cols as a single array to result
String[] currentRow = new String[colsWithValues]; //Will be 2 here for row 0
int rowIndex = 0; //Points to next empty column in currentRow[]
for (int col = 0; col < array[row].length; col++) {
if (array[row][col] != "") {
currentRow[rowIndex] = array[row][col];
}
}
//After this, for row 0, currentRow will be {abcd, zxcs}
//Just add it to our result
result[arrayIndex] = currentRol;
//After 1st iteration, result will be {{"abcd", "zxcs"}, {}}
//During 2nd iteration, arrayIndex == 1, currentRow == {"asdf"}
//On adding it to result[1], result will be {{"abcd", "zxcs"}, {"asdf"}}
【讨论】:
{{"abcd","aa"},{"asdf",""},{"",""},{"",""},{"",""},{"",""}}; 你的 valuesPresent 将是 3 但实际上你有 2 个子数组 ;)
(array[i][j] != "") 暗示它是空的,对吧?
private String[][] removeFromArray(String[][] source, String[] objToRemove) {
return Arrays.stream(source)
.filter(element -> !Arrays.equals(element , objToRemove))
.toArray(String[][]::new);
}
void example() {
final String[] empty = new String[]{"", ""};
String[][] array = {{"abcd", ""}, {"asdf", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}};
array = removeFromArray(array, empty);
}
类似的东西应该可以工作
【讨论】:
我在这里假设嵌套数组可以是任意大小,而不仅仅是 2 个元素。
创建一个接受Stream<String> 的谓词并检查是否有任何元素不为空且非空。
String[][] array= {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
Predicate<Stream<String>> arrayPredicate = element ->
element.anyMatch(ele ->Objects.nonNull(ele) && !ele.isEmpty());
现在流过原始数组并根据谓词过滤内部数组并将其收集到新数组中。
String[][] copyArray = Arrays.stream(array)
.filter(arr -> arrayPredicate.test(Arrays.stream(arr)))
.toArray(String[][]::new);
array = copyArray; // reassign to array
【讨论】:
首先,不要使用== 或!= 比较两个字符串 的相等性,即使是字符串数组:
if (array[i][j] != "") {
在上述情况下,应该是:
if (!array[i][j].equals("")) {
如果您还不太了解 Streams,那么这可能是您感兴趣的一种方式:
public static String[][] removeNullStringRows(String[][] array) {
if (array == null || array.length == 0) {
return null;
}
int validCount = 0; // Row Index Counter for the new 2D Array
/* Find out how may rows within the 2D array are valid
(where the do not consist of Null Strings {"", ""}).
This let's you know how many rows you need to initialize
your new 2D Array to. */
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (!array[i][j].equals("")) {
validCount++;
break;
}
}
}
/* Declare and initialize your new 2D Array. This is
assuming the column count is the same in all rows. */
String[][] array2 = new String[validCount][array[0].length];
validCount = 0; // Used as an index increment counter for the new 2D Array
// Iterate through the supplied 2D Array and weed out
// the bad (invalid) rows.
for (int i = 0; i < array.length; i++) { // Iterate Rows...
for (int j = 0; j < array[i].length; j++) { // Iterate Columns
/* Does this row contain anything other than a Null String ("")?
If it does then accept the entire Row into the new 2D Array. */
if (!array[i][j].equals("")) {
// Retrieve all the columns for this row
for (int k = 0; k < array[i].length; k++) {
array2[validCount][k] = array[i][k];
}
// The above small 'for' loop can be replaced with:
// System.arraycopy(array[i], 0, array2[validCount], 0, array[i].length);
validCount++; // Increment our Row Index Counter for the new 2D Array
break; // Get out of this column iterator. We already know it's good.
}
}
}
return array2; // Return the new 2D Array.
}
要使用这种方法,你可以这样做:
// Your current 2D Array
String[][] array = {
{"abcd",""}, {"asdf",""}, {"",""},
{"",""}, {"",""}, {"",""}
};
// If the supplied 2D Array is null contains no rows
// then get out of here.
if (array == null || array.length == 0) {
return;
}
// Display the original 2D Array (array) in the Console window
System.out.println("The original 2D Array:");
for (int i = 0; i < array.length;i++) {
System.out.println(Arrays.toString(array[i]));
}
// Remove all rows that contain all Null String Columns.
// Make your Array equal what is returned by our method.
array = removeNullStringRows(array);
// Display the new 2D Array (array) in the Console window.
System.out.println();
System.out.println("The New 2D Array:");
for (int i = 0; i < array.length;i++) {
System.out.println(Arrays.toString(array[i]));
}
您的控制台窗口输出应如下所示:
The original 2D Array:
[abcd, ]
[asdf, ]
[, ]
[, ]
[, ]
[, ]
The New 2D Array:
[abcd, ]
[asdf, ]
【讨论】:
你可以从这个二维数组中过滤掉所有null和empty元素,如下所示:
String[][] array = {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
String[][] nonEmptyArray = Arrays.stream(array)
.map(row -> Arrays.stream(row)
// filter out 'null' elements and empty strings
.filter(e -> e != null && e.length() > 0)
// an array of non-empty strings or an empty
// array if there are no such strings
.toArray(String[]::new))
// filter out empty arrays
.filter(row -> row.length > 0)
// an array of non-empty arrays
.toArray(String[][]::new);
// output
System.out.println(Arrays.deepToString(nonEmptyArray)); // [[abcd], [asdf]]
【讨论】: