Sri
Sri

Reputation: 159

How to remove zeros from int array?

This is my array: int[] test= new int[] {1,0,1,0,0,0,0,0,0,0}

Now I need to remove all the zeros from this array so it will display like this: Output : {1,1}

I tried this code from this link-StackOverFlow but didn't work for me.

    int j = 0;
    for (int i = 0; i < test.length; i++) {
        if (test[i] != 0)
            test[j++] = test[i];
    }
    int[] newArray = new int[j];
    System.arraycopy(test, 0, newArray, 0, j);
    return newArray;

Please help me to solve this.

Upvotes: 2

Views: 6172

Answers (3)

zardon
zardon

Reputation: 1651

I'm not familiar with Java, but if there is a Underscore or Lo-dash library you can use; then you can employ .filter functionality;

This code is from Swift;

var numbers = [1,0,1,0,0,0,0,0,0,0]
numbers = numbers.filter({ $0 != 0 })  // returns [1,1]

Upvotes: 0

arbi mahdi
arbi mahdi

Reputation: 56

if you insist to work with array you can use this :

int n = 0;
for (int i = 0; i < test.length; i++) {
    if (test[i] != 0)
        n++;
}

int[] newArray = new int[n];
int j=0;

for (int i = 0; i < test.length; i++) {
    if (test[i] != 0)
       { 
         newArray[j]=test[i]; 
         j++;
       }
}

return newArray;

Or Try to use list :

List<Integer> list_result = new ArrayList<Integer>();
for( int i=0;  i<test.length;  i++ )
{
    if (test[i] != 0)
        list_result.add(test[i]);
}
return list_result;

to parse list :

for( int i=0;  i<list_result.size();  i++ )
{
        system.out.pintln((Integer)list_result.get(i));
}

Upvotes: 2

Paul Boddington
Paul Boddington

Reputation: 37645

Use a List instead. Then you can just do list.removeAll(Collections.singleton(0));. Arrays are far harder to use for this kind of thing.

Example:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 0, 2, 0, 3, 0, 0, 4));
list.removeAll(Collections.singleton(0));
System.out.println(list);

Output: [1, 2, 3, 4]

Upvotes: 3

Related Questions