как удалить пустой элемент в многомерном массиве строк в java - PullRequest
0 голосов
/ 26 апреля 2020
String[][] array= {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};

Я хочу удалить {"",""} эти элементы из массива

Как я могу сделать это в java? Пожалуйста помоги !!!

Ответы [ 4 ]

0 голосов
/ 26 апреля 2020

Для начала не сравнивайте две строки для равенства , используя == или !=, даже для массивов строк:

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, ]
0 голосов
/ 26 апреля 2020
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);
}

Что-то подобное должно работать

0 голосов
/ 26 апреля 2020

Я предполагаю, что вложенный массив может иметь любой размер, а не только 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
0 голосов
/ 26 апреля 2020

Удалить?
Вы не можете изменить размер существующего массива.
Если вы хотите создать новый массив только с этими элементами, подсчитайте длину каждого массива, создайте новый массив на основе этих длин, добавьте элементы в новый массив.

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++;
        }
    }
}

Чтобы получить 2-й массив, легкий для понимания:

//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"}}
...