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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…