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?
The List provides removeAll() method to remove all elements of a list that are part of the collection provided.
The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c);
To remove elements at indexes
:
Collections.sort(indexes, Collections.reverseOrder()); for (int i : indexes) strs.remove(i);
Or, using the Stream API from Java 8:
indexes.sort(Comparator.reverseOrder()); indexes.stream().mapToInt(i -> i).forEach(l::remove);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With