0

I have a very basic question but apparently I can't find the solution. I have initialized an array of String of size 100 rows and 100 columns.

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

However most of the elements are empty. I want to remove those empty string but not using the different array. Let's say the non empty strings are from row 1 to 16, and from column 1 to 10. So the final output size should be

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

How to find and remove the strings from the first array and reduce the size of the array at the same time?

3
  • 2
    No, you can't change the size of an array. Commented Nov 13, 2018 at 2:23
  • so, I will always need to use a different array? Commented Nov 13, 2018 at 2:24
  • Why is “Is it possible to…” a poorly worded question? Commented Nov 13, 2018 at 2:25

5 Answers 5

1

Here is a neat way of doing it with 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;
}

Here's a test

@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);
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I wanted exactly! Thanks a lot!
0

Arrays' size cannot be changed. However, you can do this by reassigning the variable:

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

This will replace array1 with a properly sized version, without having to introduce another permanent variable (x, y, and temp can be ignored after this)

4 Comments

what will happen if I don't know the value of x and y?
I can't tell from your question, are all of the non-empty cells in a corner of the matrix or ar they spread out randomly?
they are in a corner of a matrix
then you could determine x by iterating through the first row of the array and counting how many strings you see, and determine y by iterating through the rows and counting how many of them have anything in the first position.
0

You cannot reduce the size of an array. However, you can create a method that returns a trimmed version of the old array, such as

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

2 Comments

what will happen if I don't know the value of rows and cols?
In order to create a new array of a smaller length, you'd have to know that. You can find the desired lengths by iterating through the initial array and going until you find the index where array[index-row][index-col] == null.
0

Array has fixed length. You have to replace it with another array that fit your requirement

Comments

0

As other answers and comments have advised, you can't change the size of array, you'll have to create a new one.
However, it's best to use a Collection, which will automatically resize itself.

If you still want to do it using a new array, here is how you can do it:-
I have taken an array of size 3x3, you can use the code for 100x100

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

In this example, since the max number of columns used by any row is 2, we can have the new array with just 2 columns instead of 3.

Similarly, last row is virtually empty with no non-empty strings, we can have the new array with just 2 rows instead of 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));
}

Output is [[row0 col0, row0 col2], [row1 col0, null]], which is a 2x2 array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.