Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple elements from ArrayList

Tags:

java

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?

like image 951
Jeffrey Avatar asked Feb 09 '11 21:02

Jeffrey


People also ask

How do I remove multiple elements from an ArrayList?

The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

How do you remove all elements from an ArrayList in Java?

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


2 Answers

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); 
like image 200
aioobe Avatar answered Oct 20 '22 09:10

aioobe


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()); 
like image 41
Mark Peters Avatar answered Oct 20 '22 10:10

Mark Peters