Home >Java >javaTutorial >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:
List<Book> books = new ArrayList<>(); ISBN isbn = new ISBN("0-201-63361-2"); books.removeIf(book -> book.getIsbn().equals(isbn));
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 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!