Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Null Value from String array in java

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"}; 
like image 568
Gnaniyar Zubair Avatar asked Nov 10 '10 23:11

Gnaniyar Zubair


People also ask

How do you remove null characters from a string in Java?

string. Join("", mText. Split(new string[] { "\0" }, StringSplitOptions. None));

How do you remove null from array of objects?

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.


2 Answers

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()]); 
like image 28
Kirk Woll Avatar answered Sep 22 '22 12:09

Kirk Woll


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);          } } 
like image 72
Vivin Paliath Avatar answered Sep 21 '22 12:09

Vivin Paliath