remove null value from a String array in Java


Following program creates an array with null values. Convert it a list with not-null values only and then get the array of that list.

Example

import java.util.ArrayList;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      String[] array = {"I", null, "love", null, "Java" };
      List<String> values = new ArrayList<String>();
      for(String data: array) {
         if(data != null) { 
            values.add(data);
         }
      }
      String[] target = values.toArray(new String[values.size()]);
      for(String data: target) {
         System.out.println(data + " ");
      }
   }
}

Output

I
love
Java

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements