简体   繁体   中英

Replace Null Values in Arraylist

i'm trying to replace null values in my arrayList but I get exception

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

Here is an exemple of my 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" . 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:

// 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.

in this line you are comparing the value at position x with the String null and not "with a null value":

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.

Below line is throwing NullPointerException because calling equals method on null object is not allowed in Java.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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