Remove Null Value from String array in java
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.
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
}
});
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()]);
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);
}
}