Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "minify" an array - Java

Tags:

java

arrays

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?

like image 644
Bluefire Avatar asked Dec 12 '22 01:12

Bluefire


1 Answers

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));
    }

}
like image 107
Francisco Spaeth Avatar answered Dec 27 '22 22:12

Francisco Spaeth