How Can I Safely Modify Collections While Iterating in Java?
Modifying Collections During Iteration: A Comprehensive Guide
To effectively modify collections during iteration to avoid errors like ConcurrentModificationException, there are several strategies to consider:
Collect and Remove
This method involves collecting objects to be removed during an enhanced for loop and then removing them after iteration completes. This technique is particularly useful in scenarios where deletion is the primary goal:
List<Book> books = new ArrayList<>(); ISBN isbn = new ISBN("0-201-63361-2"); List<Book> found = new ArrayList<>(); for (Book book : books) { if (book.getIsbn().equals(isbn)) { found.add(book); } } books.removeAll(found);
Using ListIterator
ListIterator provides support for both removal and addition of items during iteration. This makes it a suitable choice when modifying lists:
List<Book> books = new ArrayList<>(); ISBN isbn = new ISBN("0-201-63361-2"); ListIterator<Book> iter = books.listIterator(); while (iter.hasNext()) { if (iter.next().getIsbn().equals(isbn)) { iter.remove(); } }
JDK >= 8
Java 8 introduces additional methods for collection modification:
- removeIf: This method removes elements matching a specified predicate from the collection:
List<Book> books = new ArrayList<>(); ISBN isbn = new ISBN("0-201-63361-2"); books.removeIf(book -> book.getIsbn().equals(isbn));
- Stream API: The stream API allows for filtering and removing elements using pipelines:
List<Book> books = new ArrayList<>(); ISBN isbn = new ISBN("0-201-63361-2"); List<Book> filtered = books.stream() .filter(book -> book.getIsbn().equals(isbn)) .collect(Collectors.toList());
Sublist or Subset
For sorted lists, removing consecutive elements can be done efficiently using sublists:
List<Book> books = new ArrayList<>(); books.subList(0, 5).clear();
Considerations
The choice of modification method depends on the specific scenario and collection type. Here are some key considerations:
- The "collect and remove" technique is versatile and works with any collection.
- The ListIterator approach is efficient but only applicable to lists with supporting implementations.
- The Iterator approach supports removal but may not be universally available.
- JDK 8 methods offer efficient filtering and removal but require transferring to a new collection.
- Sublists allow for bulk removal of consecutive elements in sorted lists.
The above is the detailed content of How Can I Safely Modify Collections While Iterating in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...
