从 Java 中的字符串数组中删除空值
如何在java中从字符串数组中删除空值?
String[] firstArray = {"test1","","test2","test4",""};
我需要没有空(空)值的“firstArray”,如下所示
String[] firstArray = {"test1","test2","test4"};
如何在java中从字符串数组中删除空值?
String[] firstArray = {"test1","","test2","test4",""};
我需要没有空(空)值的“firstArray”,如下所示
String[] firstArray = {"test1","test2","test4"};
如果你想避免栅栏错误,并避免移动和删除数组中的项目,这里有一个有点冗长的解决方案,它使用: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()]);
}
}
添加以显示空字符串实例 () 和 之间的差异。null
""
null
由于这个答案大约是4.5年前,所以我添加了一个Java 8示例:
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);
}
}
如果您真的想从数组中添加/删除项目,我是否可以建议一个?List
String[] firstArray = {"test1","","test2","test4",""};
ArrayList<String> list = new ArrayList<String>();
for (String s : firstArray)
if (!s.equals(""))
list.add(s);
然后,如果你真的需要把它放回一个数组中:
firstArray = list.toArray(new String[list.size()]);