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.
clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.
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);
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 String
s 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
.
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