Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList.removeAll(), but for indices

Tags:

java

arraylist

Is there a way to do something like this:

ArrayList<String>.removeAll(ArrayList<Integer>)

With the ArrayList<Integer> being the indices that I want deleted. I know that I could iterate through the indices list and use remove(index), but I was wondering if there is a one-command way of doing so.

I know how to put this iteration into one line, my question is, if there is a way implemented by oracle.

like image 422
Azog the Debugger Avatar asked Mar 14 '18 16:03

Azog the Debugger


People also ask

What is the difference between ArrayList Clear () and removeAll () methods?

clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.

How do I use list removeAll?

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


1 Answers

You can use a Stream to iterate through the indices to remove. However, take care to remove the highest index first, to avoid shifting other elements to remove out of position.

public void removeIndices(List<String> strings, List<Integer> indices)
{
     indices.stream()
         .sorted(Comparator.reverseOrder())
         .forEach(strings::remove);
}

For removing from a list of Strings this will work, calling the proper remove(int) method. If you were to try this on a List<Integer>, then you will have to avoid calling remove(E) by calling .mapToInt(Integer::intValue) before calling forEach.

like image 120
rgettman Avatar answered Oct 19 '22 23:10

rgettman