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"};
string. Join("", mText. Split(new string[] { "\0" }, StringSplitOptions. None));
To remove all null values from an object: Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array of keys. Check if each value is equal to null and delete the null values using the delete operator.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With