0

I'm trying to remove null values from a array that is converted from a csv string.

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]
1
  • 6
    The string "null" is different from a reference being null. Commented Dec 29, 2015 at 19:05

4 Answers 4

1

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

So change this...

if (elem != null) {

To this, to account for "null"...

if (elem != null && !elem.equalsIgnoreCase("null")) {
Sign up to request clarification or add additional context in comments.

2 Comments

Consider lower casing the elem if OP wants to get rid of "NULL" or "Null"
Good call. Changed equals to equalsIgnoreCase.
1

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.

Comments

0

removeNull(String[]) works fine, it is the test that is broken. 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). That might present you with some interesting options and a more versatile final product.

Comments

0

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.