Lets say that I have an array as followed :
String[] letter = {a, b, c, e, f, }
How can I trim this array in order to get rid the empty element?
Lets say that I have an array as followed :
String[] letter = {a, b, c, e, f, }
How can I trim this array in order to get rid the empty element?
There is no "empty" element in that array. The trailing comma makes no difference - your array still has 5 elements.
If you have a real problem in real code where some elements in an array are empty (and you'll have to say what you mean by that - null value? Value referring to an empty string?) you can't change the size of an existing array, but you can create a new array, e.g. with
List<String> list = new ArrayList<String>();
for (String text : array)
{
if (text != null && text.length() > 0)
{
list.add(text);
}
}
array = list.toArray(new String[0]);
There is no empty element.
Java allows for a trailing comma after the last element in an array defined in code. So there is no empty element in your array.
In order to create an empty (null) element, you would need to do this:
String[] letter = {a, b, c, e, f, null};
Note: It is my interpretation that the OP feels that the trailing comma is adding a null element to the end of the array.
No Empty Element in your array. If you put like below then it will contains null and space also.
String[] letter = {"a", "b", "c", "e", "f", null, " h", " "};
and then you have to go through like this.
for (int i = 0; i < letter.length; i++) {
if (letter[i] != null && !letter[i].equals(" ")) {
System.out.println("Letters::::::" + letter[i]);
}
}
System.out.println("Length:::::" + letter.length);
Assuming that you did have an array with one or more null
elements at the end, you could use the code below to find the index of the first null
element and then create a copy of the array, discarding that element and anything after it.
// sample array to be trimmed
String[] array = {"1", "2", "3", null, null};
int end = Arrays.asList(array).indexOf(null);
if (end >= 0) {
String[] tmp = new String[end];
System.arraycopy(array, 0, tmp, 0, end);
array = tmp;
}
You can use this simple code snippet to delete nulls and empty strings from array` import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String data = "1, 2, ,4 , , 5 ";
String[] split = data.split(",");
split = Arrays.stream(split).filter(s -> (s != null && s.length() > 0 && !s.trim().equals("")))
.toArray(String[]::new);
for(String str:split){
System.out.println(str.trim());
}
}
}`