Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing unfilled values or null values from array of String in Java

Tags:

java

string

I have following String Array tmp = [null, null, null, Mars, Saturn, Mars] coming after doing the operation - allSig[d3].split(" "); where allSig is an array of Strings. The null value is empty value in the array. Now I want to remove the null. For this I am using

tmp[indexNumber] != null is not working and giving true ; taking null as the value. Even if i am using "null" as a string is not working.

How to remove this.

public static String[] removeElements(String[] allElements) {
    String[] _localAllElements = new String[allElements.length];

    for (int i = 0; i < allElements.length; i++)
        if (allElements[i] != null)
            _localAllElements[i] = allElements[i];

    return _localAllElements;
}
like image 654
Kumar Avatar asked Aug 17 '12 08:08

Kumar


People also ask

How do you remove Blank values from an array in Java?

Below are the methods to remove nulls from a List in Java: Using List. remove() List interface provides a pre-defined method remove(element) which is used to remove a single occurrence of the element passed, from the List, if found.

How do you remove null values from an array?

To remove a null from an array, you should use lodash's filter function. It takes two arguments: collection : the object or array to iterate over. predicate : the function invoked per iteration.

How do you remove null characters from a string in Java?

Solution 1temp = temp. Replace("\0", string. Empty); will remove the null characters.


2 Answers

Simplest Solution :

 public static String[] clean(final String[] v) {
    List<String> list = new ArrayList<String>(Arrays.asList(v));
    list.removeAll(Collections.singleton(null));
    return list.toArray(new String[list.size()]);
}
like image 171
AZ_ Avatar answered Oct 14 '22 19:10

AZ_


public static String[] clean(final String[] v) {
  int r, w;
  final int n = r = w = v.length;
  while (r > 0) {
    final String s = v[--r];
    if (!s.equals("null")) {
      v[--w] = s;
    }
  }
  return Arrays.copyOfRange(v, w, n);
}

or

public static String[] clean(final String[] v) {
  int r, w, n = r = w = v.length;
  while (r > 0) {
    final String s = v[--r];
    if (!s.equals("null")) {
      v[--w] = s;
    }
  }
  final String[] c = new String[n -= w];
  System.arraycopy(v, w, c, 0, n);
  return c;
}

Works fine...

public static void main(final String[] argv) {
  final String[] source = new String[] { "Mars", "null", "Saturn", "null", "Mars" };
  assert Arrays.equals(clean(source), new String[] { "Mars", "Saturn", "Mars" });
}
like image 42
obataku Avatar answered Oct 14 '22 17:10

obataku