Remove all zeros from array
You can achieve this with one loop only. Whether this is better or more clear is a matter of personal taste I am afraid.
int[] array = {0, 5, 6, 0, 0, 2, 5};
int[] temp = new int[array.length];
int numberOfZeros = 0;
for (int i=0; i<array.length; i++){
if (array[i] != 0){
temp[i-numberOfZeros] = array[i];
} else {
numberOfZeros++;
}
}
int[] result = new int[temp.length-numberOfZeros];
System.arraycopy(temp, 0, result, 0, result.length);
Another option would be to use a List
implementation like ArrayList
from which you can just remove elements, but then you will have to work with Integer
instances and not with int
s
List<Integer> originalList = ....;
Iterator<Integer> iterator = originalList.iterator();
while ( iterator.hasNext() ) {
Integer next = iterator.next();
if ( next == 0 ){
iterator.remove();
}
}
//convert to array if needed
Integer[] result = originalList.toArray( new Integer[originalList.size()]);
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;
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]
With Java 8 you can make a stream out of the array, apply .filter() and then convert it back into an array :
int[] array = {0, 5, 6, 0, 0, 2, 5};
int[] filteredArray = Arrays.stream(array).filter(num -> num != 0).toArray();
// filteredArray = {5, 6, 2, 5};