Removing unfilled values or null values from array of String in Java

前端 未结 7 1284
醉话见心
醉话见心 2020-12-16 02:22

I have following String Array tmp = [null, null, null, Mars, Saturn, Mars] coming after doing the operation - allSig[d3].split(\" \"); where

7条回答
  •  自闭症患者
    2020-12-16 02:47

    If you want the array to contain only the non-null values (i.e. the resulting array would be ["Mars", "Saturn", "Mars"]), then I would look at this as a two part problem.

    First, you must identify what the size of the new array should be. From inspection, it's easy to see that it's 3, but you will need to need to count them to calculate this programmatically. You can do this by saying:

    // Calculate the size for the new array.
    int newSize = 0;
    for (int i = 0; i < allElements.length; i++)    {
        if (allElements[i] != null) {
            newSize++;
        }
    }
    

    Secondly, you will need to create a new array with that size. Then you can put all of the non-null elements into your new array, as you have done above.

    // Populate the new array.
    String[] _localAllElements = new String[newSize];
    int newIndex = 0;
    for (int i = 0; i < allElements.length; i++) {
        if (allElements[i] != null) {
            _localAllElements[newIndex] = allElements[i];
            newIndex++;
        }
    }
    
    // Return the new array.
    return _localAllElements;
    

    You can just combine these two components as the new content of your results method. See the full combined code and live sample output here.

提交回复
热议问题