Remove elements from an arraylist in Java

Опубликовано: 13 Март 2018
на канале: 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  


На этой странице сайта вы можете посмотреть видео онлайн Remove elements from an arraylist in Java длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь Dan Vega 13 Март 2018, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 24,727 раз и оно понравилось 284 зрителям. Приятного просмотра!