[英]Remove null values from java array
I'm trying to remove null values from a array that is converted from a csv string. 我正在尝试从从csv字符串转换而来的数组中删除空值。
This is what i'm trying to do. 这就是我想要做的。
public class ArrayTest {
public static void main(String[] args) {
String commaSeparated = "item1,null,item1,null,item3";
String [] items = commaSeparated.split(",");
String[] result = removeNull(items);
System.out.println(Arrays.toString(result));
}
public static String[] removeNull(String[] items) {
ArrayList<String> aux = new ArrayList<String>();
for (String elem : items) {
if (elem != null) {
aux.add(elem);
}
}
return (String[]) aux.toArray(new String[aux.size()]);
}
}
I still get the output as below which still has the null values. 我仍然得到如下的输出,其中仍然具有空值。 Can you please point me what is wrong with this 你能告诉我这是怎么了吗
[item1, null, item1, null, item3]
Change 更改
if (elem != null)
to 至
if (!elem.equals("null"))
The .split
function returns an array of strings, so those elements that you expected to be null
are not actually, they are "null"
strings. .split
函数返回一个字符串数组,因此您期望为null
那些元素实际上不是,它们是"null"
字符串。
Your removeNulls()
method does in fact remove null Strings
, but remember when you are doing String.split
, you are actually creating a non-null String
whose value happens to be "null". 实际上,您的removeNulls()
方法确实删除了null Strings
,但请记住,当您执行String.split
,实际上是在创建一个非null的String
其值恰好是“ null”。
So change this... 所以改变这个...
if (elem != null) {
To this, to account for "null"... 为此,要考虑“空” ...
if (elem != null && !elem.equalsIgnoreCase("null")) {
removeNull(String[])
works fine, it is the test that is broken. removeNull(String[])
可以正常工作,它是测试失败了。 Consider creating test input like this: 考虑创建这样的测试输入:
public static void main(String[] args) {
String [] items = {"item1",null,"item1",null,"item3"};
String[] result = removeNull(items);
System.out.println(Arrays.toString(result));
}
As an aside, this is a good place to think about generics. 顺便说一句,这是考虑泛型的好地方。 What if you wanted your method signature to look like this T[] removeNull(T[] input)
. 如果您希望方法签名看起来像这样T[] removeNull(T[] input)
该T[] removeNull(T[] input)
? That might present you with some interesting options and a more versatile final product. 这可能会为您提供一些有趣的选项和更通用的最终产品。
with streams: 与流:
public static void main(String[] args) {
String commaSeparated = "item1,null,item1,null,item3";
String[] items = commaSeparated.split(",");
String[] result = Arrays.stream(items)
.filter(s -> s != null && !s.equals("null"))
.toArray(String[]::new);
System.out.println(Arrays.toString(result));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.