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"};
JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
Gnaniyar Zubair
  • 8,114
  • 23
  • 61
  • 72
  • 39
    `null` is completely different from "empty string" in Java. That's your first problem. – JSBձոգչ Nov 10 '10 at 23:55
  • 1
    null is not "". "" is an empty, but perfectly valid string. – EboMike Nov 10 '10 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? –  Nov 10 '10 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. – Gnaniyar Zubair Nov 11 '10 at 00:00
  • Then you might want to update your question to reflect the fact that you mean empty string and not null. – Steve Kuo Nov 11 '10 at 00:11
  • possible duplicate of [How do I remove objects from an Array in java?](http://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java) – McDowell May 09 '11 at 10:24

8 Answers8

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

    }
}
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
25

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.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
  • `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. – Drizzle53 Sep 20 '22 at 18:46
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()]);
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
  • 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. –  Nov 11 '10 at 00:04
  • You should use `String.isEmpty()` instead of `String.equals("")` – Steve Kuo Nov 11 '10 at 00:11
  • @Steve, lots of people feel the way you do. I just (personally) think that `s.equals("")` is more readable -- less abstract. – Kirk Woll Nov 11 '10 at 01:04
  • @DaveJarvis, it's rather self-evident that the OP was confusing the empty string with `null`. – Kirk Woll Aug 11 '12 at 13:45
  • 2
    You're right, Kirk. Yet the possibility of a `NullPointerException` remains. That is a bug. – Dave Jarvis Aug 11 '12 at 17:51
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);
Ian S.
  • 1,831
  • 9
  • 17
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
    }
});
Emil
  • 13,577
  • 18
  • 69
  • 108
  • 2
    Along the same approach, one could use the FunctionalJava library. –  Nov 11 '10 at 22:00
  • @Emil And then, how do you put what is inside `st` back inside `firstArray`? – Abdull Feb 20 '13 at 01:28
  • @Abdull: No need for that since firstArray is not modified.The filtering happen's lazily.i.e while iterating the array. – Emil Feb 20 '13 at 06:10
  • 2
    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; – Sagar May 12 '14 at 21:04
2

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;
}
Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
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.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
-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?

Mud
  • 28,277
  • 11
  • 59
  • 92
  • 1
    Then the question becomes: "How can you resize an Array in Java"? :-) –  Nov 10 '10 at 23:58
  • That doesn't really do what he wants. This just copies data around. It doesn't do anything to make the array smaller. – mlathe Nov 11 '10 at 00:00
  • 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. – Gnaniyar Zubair Nov 11 '10 at 00:01
  • 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* – Mud Nov 11 '10 at 02:51