remove null value from a String array in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 06-Feb-2018 14:38:14
Advertisements