filmov
tv
Remove elements from an arraylist in Java

Показать описание
In this tutorial, we are going to learn how to safely remove elements from an ArrayList in Java while using a for loop to loop over that same list.
The other day I was using a for loop in Java to loop over a collection. Inside of that loop, I was evaluating each element to see if it met some criteria. If it did meet that criteria I wanted to remove that element from the collection.
Each time I tried to remove the element Java would throw a concurrent modification exception and my program would fail. There is actually a really good reason this happens. If you understand what is happening underneath the hood when we use a for loop it all makes sense. We are using an iterator to loop over the collection while using the collection to remove the element and this never updates the iterator to say "I removed an element".
In this tutorial, we will look at one way to solve it and then an even easier way to fix this problem. In Java 8 a new method was added to the collections interface called removeIf. This method takes a predicate and makes it super easy for us to remove items from a collection if they meet some criteria.
I really hope you enjoyed this tutorial and if you did please let me know what other tutorials you might enjoy seeing. Please Subscribe to this channel and leave a comment below.
Thank You
Dan Vega
The other day I was using a for loop in Java to loop over a collection. Inside of that loop, I was evaluating each element to see if it met some criteria. If it did meet that criteria I wanted to remove that element from the collection.
Each time I tried to remove the element Java would throw a concurrent modification exception and my program would fail. There is actually a really good reason this happens. If you understand what is happening underneath the hood when we use a for loop it all makes sense. We are using an iterator to loop over the collection while using the collection to remove the element and this never updates the iterator to say "I removed an element".
In this tutorial, we will look at one way to solve it and then an even easier way to fix this problem. In Java 8 a new method was added to the collections interface called removeIf. This method takes a predicate and makes it super easy for us to remove items from a collection if they meet some criteria.
I really hope you enjoyed this tutorial and if you did please let me know what other tutorials you might enjoy seeing. Please Subscribe to this channel and leave a comment below.
Thank You
Dan Vega
Комментарии