Jeffrey Jeffrey - 1 year ago 91
Java Question

Remove multiple elements from ArrayList

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

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

Answer Source

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);


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

Collections.sort(indices, Collections.reverseOrder());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download