Chris G
Chris G

Reputation: 469

Removing Null elements in an array

I'm reading from an XML file to populate some data structures and I run into this sort of problem when I inspect my final structure:

arrayName
 [0] = null
 [1] = input
 [2] = null
 [3] = input

etc

input is what I want, and the type is my own class.

I'm used to C# so I'd use LINQ to get rid of them normally, idea for doing something like this in Java?

I'm going to look at what's wrong with the code that's making it happen but for now I need a quick solution.

Ideas?

EDIT:

I found the issue, I create an array of size doc.getChildNodes().getLength(), and when I'm setting elements in the array (while looping through), I check if

 getNodeType() == Node.ELEMENT_NODE) 

And it doesn't work half the time. Problem is, I initialise the array based on the size, so half the array gets filled.

Ideas?

Upvotes: 0

Views: 1227

Answers (4)

ashes999
ashes999

Reputation: 10163

Unfortunately, there's nothing like LINQ in Java. The best thing would be probably checking for null beforehand, and only inserting if the element is not null, eg. (assuming your class name is InputClass:

InputClass c = parseFromXml(...);
if (c != null) {
    myList.add(c);
}

Alternatively, you can remove nulls by iterating and copying (I use a list as an intermediary artifact):

InputClass[] removeNulls(InputClass[] original) {
    List<InputClass> nonNulls = new ArrayList<InputClass>();
    for (InputClass i : original) {
        if (i != null) {
            nonNulls.add(i);
        }
    }

    return nonNulls.toArray(new InputClass[0]);
}

You can also use generics and make your method <T> removeNulls(T[] original) instead.

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

If you're not having excessive amounts of data, you could just blend it through a few collections.

public class Main {
    public static void main(String[] args) {
        String[] arr = {"haha", "hoho", null, "hihi", null };
        System.out.println(Arrays.toString(arr));

        Set<String> set = new HashSet<>(Arrays.asList(arr));
        set.remove(null);
        arr = new String[set.size()];
        arr = set.toArray(arr);

        System.out.println(Arrays.toString(arr));
    }
}

Output:

[haha, hoho, null, hihi, null]
[hoho, haha, hihi]

Keep in mind that this first allocates the original array, then creates a list from that array, then creates a hashset from that list and eventually puts everything back in the original array.

If you're having a very large amount of data it might constipate you a little but otherwise it's very easy to read and really just uses built-in features to reach what you want.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

It sounds like you want a method to give you a new Array with the null values removed; perhaps something like this -

public static <T> T[] removeNulls(T[] in) {
  if (in == null) {
    return in;
  }
  Class<?> cls = null;
  List<T> al = new ArrayList<T>();
  for (T t : in) {
    if (t != null) {
      if (cls == null) {
        cls = t.getClass();
      }
      al.add(t);
    }
  }
  @SuppressWarnings("unchecked")
  T[] out = (T[]) Array.newInstance(cls, al.size());
  return al.toArray(out);
}

Upvotes: 0

Hauke Ingmar Schmidt
Hauke Ingmar Schmidt

Reputation: 11607

Arrays are immutable in Java (not their contents, the array itself). There is no such thing as a dynamic sized array or changing of the length. So you would iterate, count, create a new array, copy... or use an appropriate datastructure in the first place, maybe even one that capsules the creation of new arrays and offers manipulation methods like ArrayList.

Something like LINQ does not exist yet, you need some explicit object that capsules the manipulation or filtering.

Upvotes: 1

Related Questions