43

How to remove null value from String array in java?

String[] firstArray = {"test1","","test2","test4",""};

I need the "firstArray" without null ( empty) values like this

String[] firstArray = {"test1","test2","test4"};
6
  • 39
    null is completely different from "empty string" in Java. That's your first problem. Commented Nov 10, 2010 at 23:55
  • 1
    null is not "". "" is an empty, but perfectly valid string. Commented Nov 10, 2010 at 23:55
  • There is no null value in that array. There is, however, an empty sting (a non-null String object with a length of 0). Anyway, what have you tried? Commented Nov 10, 2010 at 23:55
  • yes you are right. null is different from "". just i wanted to removed all empty strings and should get another "String Array" without Empty strings as i mentioned. Commented Nov 11, 2010 at 0:00
  • Then you might want to update your question to reflect the fact that you mean empty string and not null. Commented Nov 11, 2010 at 0:11

8 Answers 8

85

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

    List<String> list = new ArrayList<String>();

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

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

Comments

28

It seems no one has mentioned about using nonNull method which also can be used with streams in Java 8 to remove null (but not empty) as:

String[] origArray = {"Apple", "", "Cat", "Dog", "", null};
String[] cleanedArray = Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new);
System.out.println(Arrays.toString(origArray));
System.out.println(Arrays.toString(cleanedArray));

And the output is:

[Apple, , Cat, Dog, , null]

[Apple, , Cat, Dog, ]

If we want to incorporate empty also then we can define a utility method (in class Utils(say)):

public static boolean isEmpty(String string) {
        return (string != null && string.isEmpty());
    }

And then use it to filter the items as:

Arrays.stream(firstArray).filter(Utils::isEmpty).toArray(String[]::new);

I believe Apache common also provides a utility method StringUtils.isNotEmpty which can also be used.

1 Comment

Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new); Worked for me.. great workaround when you have to work with an array rather than a list in already defined function that you dont want to rewrite.
20

If you actually want to add/remove items from an array, may I suggest a List instead?

String[] firstArray = {"test1","","test2","test4",""};
ArrayList<String> list = new ArrayList<String>();
for (String s : firstArray)
    if (!s.equals(""))
        list.add(s);

Then, if you really need to put that back into an array:

firstArray = list.toArray(new String[list.size()]);

5 Comments

Haha. You implemented what I described! :-) My one improvement would be to pass a new String[0] to the toArray though -- it will create a new array with the correct size as needed.
You should use String.isEmpty() instead of String.equals("")
@Steve, lots of people feel the way you do. I just (personally) think that s.equals("") is more readable -- less abstract.
@DaveJarvis, it's rather self-evident that the OP was confusing the empty string with null.
You're right, Kirk. Yet the possibility of a NullPointerException remains. That is a bug.
4

Using Google's guava library

String[] firstArray = {"test1","","test2","test4","",null};

Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
    @Override
    public boolean apply(String arg0) {
        if(arg0==null) //avoid null strings 
            return false;
        if(arg0.length()==0) //avoid empty strings 
            return false;
        return true; // else true
    }
});

4 Comments

Along the same approach, one could use the FunctionalJava library.
@Emil And then, how do you put what is inside st back inside firstArray?
@Abdull: No need for that since firstArray is not modified.The filtering happen's lazily.i.e while iterating the array.
if(Strings.isNullOrEmpty(str)) return false; could be used instead of if(arg0==null) //avoid null strings return false; if(arg0.length()==0) //avoid empty strings return false;
4

This is the code that I use to remove null values from an array which does not use array lists.

String[] array = {"abc", "def", null, "g", null}; // Your array
String[] refinedArray = new String[array.length]; // A temporary placeholder array
int count = -1;
for(String s : array) {
    if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
        refinedArray[++count] = s; // Increments count and sets a value in the refined array
    }
}

// Returns an array with the same data but refits it to a new length
array = Arrays.copyOf(refinedArray, count + 1);

1 Comment

There is an off-by-one error in last line. Should be count + 1
3

Quite similar approve as already posted above. However it's easier to read.

/**
 * Remove all empty spaces from array a string array
 * @param arr array
 * @return array without ""
 */
public static String[] removeAllEmpty(String[] arr) {
    if (arr == null)
        return arr;

    String[] result = new String[arr.length];
    int amountOfValidStrings = 0;

    for (int i = 0; i < arr.length; i++) {
        if (!arr[i].equals(""))
            result[amountOfValidStrings++] = arr[i];
    }

    result = Arrays.copyOf(result, amountOfValidStrings);

    return result;
}

1 Comment

It might be readable. However code looks little verbose.
1

A gc-friendly piece of code:

public static<X> X[] arrayOfNotNull(X[] array) {
    for (int p=0, N=array.length; p<N; ++p) {
        if (array[p] == null) {
            int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
            X[] res = Arrays.copyOf(array, m);
            for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
            return res;
        }
    }
    return array;
}

It returns the original array if it contains no nulls. It does not modify the original array.

Comments

-1

Those are zero-length strings, not null. But if you want to remove them:

firstArray[0] refers to the first element
firstArray[1] refers to the second element

You can move the second into the first thusly:

firstArray[0]  = firstArray[1]

If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

4 Comments

Then the question becomes: "How can you resize an Array in Java"? :-)
That doesn't really do what he wants. This just copies data around. It doesn't do anything to make the array smaller.
thanks. But if i know the position where empty will come, i can do as u said. But empty strings generating dynamically. I cant predict in which position empty ( zero-length) will come.
Yes, but s.size() == 0 will tell you a string is zero-length. The idea was for you to iterate through the array shifting elements over zero-length elements. The question was so trivial I assumed it was homework and didn't want to give you the whole answer, but apparently that's what's getting voted up. shrug

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.