Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all zeros from array

I have an array:

[0, 5, 6, 0, 0, 2, 5]

I would like to remove all zeros from it, so that this returns (keeping the same order):

[5, 6, 2, 5]

Is there any easier way to remove all zeros than the following?

int[] array = {0, 5, 6, 0, 0, 2, 5};
        int len = 0;
        for (int i=0; i<array.length; i++){
            if (array[i] != 0)
                len++;
        }
        int [] newArray = new int[len];
        for (int i=0, j=0; i<array.length; i++){
            if (array[i] != 0) {
                newArray[j] = array[i];
                j++;
            }
        }

I haven't been able to find any method in the Arrays class, and Google/SO searches didn't give me any good answers.

like image 274
Hidde Avatar asked Jan 08 '12 11:01

Hidde


2 Answers

This is one of those rare cases where it is easier to show it in code than to explain in plain English:

int targetIndex = 0;
for( int sourceIndex = 0;  sourceIndex < array.length;  sourceIndex++ )
{
    if( array[sourceIndex] != 0 )
        array[targetIndex++] = array[sourceIndex];
}
int[] newArray = new int[targetIndex];
System.arraycopy( array, 0, newArray, 0, targetIndex );
return newArray;
like image 186
Mike Nakis Avatar answered Sep 20 '22 21:09

Mike Nakis


How about this:

Integer[] numbers = {1, 3, 6, 0, 4, 0, 3};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(numbers));
list.removeAll(Arrays.asList(Integer.valueOf(0)));
numbers = list.toArray(new Integer[list.size()]);
System.out.println(Arrays.toString(numbers));

OUTPUT:

[1, 3, 6, 4, 3]
like image 42
Eng.Fouad Avatar answered Sep 19 '22 21:09

Eng.Fouad