How to remove null values from a String array in Java in various ways

By Saruque Ahamed Mollick

In this Java tutorial, I will show you how to remove null value from String array in Java easily.

In order to remove null values from a String array in Java, there are plenty of methods you can apply. I will show you how to do this with a few easy examples.

So, we need to create a String array first and add some elements to it. Remember to add one or more null values too. As our main aim is to create a Java program to remove null values from a String array.

how to convert Object array to String array in java

Remove null value from String array in Java

In the below example I will create a String array having some null values. Thereafter, I will put all the not null elements in a List. Then I will use list.toArray() method.

Guess The Number Game Using Java with Source Code



import java.util.*;
  public class Myclass {
  public static void main( String[] args ) {
    String[] array_with_null = {"sometext", "", "sometext2", null, "sometext3", null};
    List<String> list_without_null = new ArrayList<String>();
    for(String new_string : array_with_null ) {
        if(new_string != null && new_string.length() > 0) {
                       list_without_null.add(new_string);
          }
}
    array_with_null = list_without_null.toArray(new String[list_without_null.size()]);
   }
}

I have used both an “” – empty string element and null – element to show the difference between these two.

in Java 8 you can try these:

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

How to convert an image to byte array in Java

FizzBuzz Problem In Java- A java code to solve FizzBuzz problem

If you got better methods or suggestions feel free to comment in the below comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *