Jeffrey Jeffrey - 24 days ago 6
Java Question

Remove multiple elements from ArrayList

I have a bunch of indexes and I want to remove elements at these indexes from an

ArrayList
. I can't do a simple sequence of
remove()
s because the elements are shifted after each removal. How do I solve this?

Answer

Sort the indices in descending order and then remove them one by one. If you do that, there's no way a remove will affect any indices that you later want to remove.

How you sort them will depend on the collection you are using to store the indices. If it's a list, you can do this:

List<Integer> indices;
Collections.sort(indices, new Comparator<Integer>() {
   public int compare(Integer a, Integer b) {
      //todo: handle null
      return b.compareTo(a);
   }
}

Edit

@aioobe found the helper that I failed to find. Instead of the above, you can use

Collections.sort(indices, Collections.reverseOrder());