So suppose I create an array with 5 spaces, like so - String[] myArray = new String[5]
. Then suppose I define some of those items, but leave some of them null (or whatever the Java term is for an undefined array item/variable), like so:
myArray[0] = "foo";
myArray[2] = "bar";
myArray[4] = "foobar";
Is there a way I can "minify" that array, squeezing out all the null items (not changing the size of it)? So that the index of "foo" stays at 0, but "bar"'s index becomes 1, and "foobar" resides at 2, with the last 2 spaces being empty? Long story short - shuffle around the items in an array, pushing all the null items to the end, while maintaining the relative order of the other items. Is there already a predefined Java method for that, or do I need to make my own?
You could use the following approach (without overhead of Collections instance):
import java.util.Arrays;
public class ArraySample {
public static void main(final String[] args) {
String[] src = new String[] { "foo", null, "bar", null, "foobar" };
String[] dest = new String[src.length];
int i = 0;
for (String s : src) {
if (s != null) {
dest[i++] = s;
}
}
System.out.println(Arrays.toString(src));
System.out.println(Arrays.toString(dest));
}
}
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