Question: Let's say I have this List

```
List<Integer> grades = Arrays.asList(9,8,1,0,7,0,0,3);

```

I want to move all zeros to the last indexes .. So I want the output to be something like:

```
9,8,1,7,3,0,0,0

```

I can do that with simple arrays but I still didn't figure out how to do that in ArrayList.

Answer: 
You can sort the list accordingly using [Comparator.comparing](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html), to move all `0` to last and not to sort the remaining values

```
grades.sort(Comparator.comparing(value -> value == 0 ? 1 /* sort last */ : 0 /* don't sort */));  //[9, 8, 1, 7, 3, 0, 0, 0]

```
For a faster *O(n)* implementation than using an *O(n log(n))* `sort()` solution, do it the same way you'd do it for an array:

```java
int j = 0;
for (Integer value : grades) {
    if (value != 0) {
        grades.set(j++, value);
    }
}
while (j < grades.size()) {
    grades.set(j++, 0);
}

```

Of course, using `set(int, ?)` can be bad for performance if not an `ArrayList`, so it'd be better to use an updatable iterator, i.e. a `ListIterator`:

```java
ListIterator<Integer> iter = grades.listIterator();
for (Integer value : grades) {
    if (value != 0) {
        iter.next(); // No need to call hasNext() first
        iter.set(value);
    }
}
while (iter.hasNext()) {
    iter.next();
    iter.set(0);
}

```

For comparison, here is the comparable array solution:

```java
int[] grades = {9,8,1,0,7,0,0,3};

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

```