简体   繁体   English

替换 Arraylist 中的 Null 值

[英]Replace Null Values in Arraylist

i'm trying to replace null values in my arrayList but I get exception我正在尝试替换 arrayList 中的 null 值,但出现异常

java.lang.NullPointerException

I have tried different way:我尝试了不同的方式:

Data.replaceAll(s -> s.replaceAll(" null", "")); 

And:和:

for(int x = 0; x < Data.size(); x++)
          {
                if(Data.get(x).equals("null") == true)
                {
                    Data.set(x, "");
                }
          }

And:和:

for(int x = 0; x < Data.size(); x++)
          {
                if(Data.get(x).equals(null) == true)
                {
                    Data.set(x, "");
                }
          }

but an exception is throw java.lang.NullPointerException但异常是抛出java.lang.NullPointerException

Here is an exemple of my arrayList:这是我的 arrayList 的示例:

[0050568D6268, null, A001, A, T3, Principal, COL - Test, 4-Lock, Com. On Stage, Social, RDC, null, null, null, null, -1, null, -1, 0, -1, 99, 53]

I'm looking for any help thanks.我正在寻找任何帮助谢谢。

The values in your list seem to be actual null s and not strings with "null" .您列表中的值似乎是实际的null ,而不是带有"null"的字符串。 You can replace these with "" by:您可以通过以下方式将它们替换为""

data.replaceAll(t -> Objects.isNull(t) ? "" : t);

You can remove them with:您可以使用以下方法删除它们:

data.removeIf(Objects::isNull)

I think you want to use map() here:我想你想在这里使用map()

// given list data
data = data.stream()
    .map(s -> Objects.isNull(s) ? "" : s)
    .collect(Collectors.toList());

This would return a list identical to the input, except with all null values replaced by empty string.这将返回一个与输入相同的列表,除了所有null值被空字符串替换。

in this line you are comparing the value at position x with the String null and not "with a null value":在这一行中,您将 position x处的值与字符串null进行比较,而不是“与 null 值”进行比较:

if(Data.get(x).equals("null") == true)

Replace this comparison by:将此比较替换为:

if(Data.get(x) == null)

We can not call any method on a null object, that is the reason why you get a NullPointerException.我们不能在 null object 上调用任何方法,这就是你得到 NullPointerException 的原因。

Below line is throwing NullPointerException because calling equals method on null object is not allowed in Java.下面的行抛出 NullPointerException,因为在 Java 中不允许在 null object 上调用equals方法。

Data.get(x).equals("null")

So replacing above with below will solve the issue.因此,将上面替换为下面将解决问题。

Data.get(x) == null

Also, there is no need for the extra comparison with == true .此外,不需要与== true进行额外比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM