Languages
[Edit]
EN

Java - iterate over List and remove indicated items

0 points
Created by:
Jasmin
395

In this article, we would like to show you how to iterate over List and remove indicated items in Java.

Note:

By iterating and deleting, we change the structure of the list. After deleting an element, loop iterators get lost, that's why the API was issued.

1. Using iterator

Edit

In this example, we use an iterator to remove indicated items from the letters ArrayList.

Output:

2. Using Collection.removeIf()

Edit

In this example, we use Java 8 removeIf() method to remove indicated elements from the letters ArrayList.

Output:

3. Collect and remove using removeAll()

Edit

In this example, we collect indicated elements in the new ArrayList, then we use removeAll() method that removes all the collected elements from the original ArrayList.

Output:

4. Using stream

Edit

In this example, we create an instance of a stream from the letters ArrayList, filter each element and collect the result in the new filteredLetters.

Output:

5*. Using reversed for loop

Edit

In this example, we remove all items from the letters ArrayList using reversed for loop.

Output:

Note:

This solution is inefficient and not recommended.

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join