As far as I know removing elements from arrays is not trivial. Instead of multiple iterative loops, the best way to actually do it is to covert it to ArrayList, add all the elements to the collection and remove the unneccesary elements. This method is particularly useful when the element removed is known and occurs multiple times, like “null” in a string array.
example.
I had an array of strings, which was result of a regex pattern match. it is named as “sentArray2”. To remove the null elements from it, I successfully implemented this following code.
The implementation is like this:
String array —–> ArrayList —-> Update(remove elements) Array list –> Convert back into string array ( I converted back into a new one but its not necessary).
// Create an ArrayList to remove null elements easily
ArrayList sentenceFinal = new ArrayList();
// Step to add all the elements into the ArrayList
for (int e=0;e<sentArray2.length;e++)
{
Collections.addAll(sentenceFinal, sentArray2[e]);
}
// Step to remove all the null elements in a single shot.
sentenceFinal.removeAll(Collections.singleton(null));
// Converting the ArrayList back to String array
String[] sentFinal = new String[sentenceFinal.size()];
sentenceFinal.toArray(sentFinal);
