从java中的字符串数组中删除空值 [英] Remove Null Value from String array in java
本文介绍了从java中的字符串数组中删除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
java中如何去除String数组中的空值?
How to remove null value from String array in java?
String[] firstArray = {"test1","","test2","test4",""};
我需要像这样没有空(空)值的firstArray"
I need the "firstArray" without null ( empty) values like this
String[] firstArray = {"test1","test2","test4"};
推荐答案
如果你想避免 fencepost 错误并避免移动和删除数组中的项目,这里有一个使用 List
的有点冗长的解决方案:
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()]);
}
}
添加了 null
以显示空 String 实例 (""
) 和 null
之间的区别.
Added null
to show the difference between an empty String instance (""
) and null
.
由于这个答案大约有 4.5 年的历史,所以我添加了一个 Java 8 示例:
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);
}
}
这篇关于从java中的字符串数组中删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文