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;
}
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.
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.
Solution 1temp = temp. Replace("\0", string. Empty); will remove the null characters.
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()]);
}
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" });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With