Home >Java >javaTutorial >How Can I Safely Modify Collections While Iterating in Java?

How Can I Safely Modify Collections While Iterating in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 22:45:15825browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn