The algorithm you have used has me a little confused. You have sorted the data in-place in the input List. Don't get me wrong, this is a useful thing to do, but I am not sure it is in the spirit of the question.... though, it can be interpreted that way.
Assuming your data is sorted, consider the following:
Integer previous = null;
boolean first = true;
for (Iterator<Integer> iterator = list.listIterator(); iterator.hasNext();) {
Integer current = iterator.next();
if (!first && Objects.equals(current, previous)) {
iterator.remove();
}
first = false;
previous = current;
}
Essentially, iterate through the (sorted) items, and if the item is the same as the previous item, ignore it. This is very similar to Brythan's solution (which gets a +1 from me), but note the different way I handle the first element in the list, compared to him.
If the list is not sorted, and you cannot have buffer, then the best system to use would be the ListIterator, and not the plain Iterator. You have much more flexibility with that....
for (ListIterator listIt = list.listIterator(list.size()); listIt.hasPrevious();) {
Integer current = listIt.previous();
listIt.next(); // make the iterator go forward again....
while (listIt.hasNext()) {
Integer following = listIt.next();
if (Objects.equals(current, following) {
listIt.remove(); // remove the matching following items...
break; // no more matches expected.
}
}
// move forward again to our current position....
do {
forward = listIt.previous();
} while (!Objects.equals(current, forward));
}
The above will remove all 'following' items in the list that are equal to any item prior to them.
Note the iterator goes from the end to the beginning. For each item in the list, it scans forward from there to see if there's a match.
This is an \$O(n^2)\$ operation, and is slower as a result, but it does not require sorting the data.