Remove elements from an arraylist in Java

Veröffentlicht am: 13 März 2018
auf dem Kanal: Dan Vega
24,727
284

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
http://therealdanvega.com/blog
  / therealdanvega  
  / therealdanvega  
  / danvega  


Auf dieser Seite können Sie das Online-Video Remove elements from an arraylist in Java mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Dan Vega 13 März 2018 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 24,727 Mal angesehen und es wurde von 284 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!