user2628187
user2628187

Reputation: 307

Remove null values from java array

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]

Upvotes: 0

Views: 517

Answers (4)

Rustam
Rustam

Reputation: 1407

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

Upvotes: 0

Andreas
Andreas

Reputation: 5103

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.

Upvotes: 0

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

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.

Upvotes: 1

Todd
Todd

Reputation: 31690

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")) {

Upvotes: 1

Related Questions