---
title: "Calling remove in foreach loop in Java"  
description: "Calling remove in foreach loop in Java"  
author: "Anonymous User"  
published: 2015-09-03  
updated: 2015-09-03  
canonical: https://www.mindstick.com/forum/33436/calling-remove-in-foreach-loop-in-java  
category: "java"  
tags: ["java", "collection"]  
reading_time: 2 minutes  

---

# Calling remove in foreach loop in Java

In [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming), is it [legal](https://www.mindstick.com/articles/43952/legal-issues-for-stress-at-work) to call [remove](https://yourviews.mindstick.com/story/4554/8-harmful-weeds-to-remove-from-garden) on a [collection](https://www.mindstick.com/articles/1718/collections-in-java) when iterating through the collection using a [foreach loop](https://www.mindstick.com/forum/182/problem-in-getting-the-value-from-array-by-using-foreach-loop)? For [instance](https://www.mindstick.com/forum/155658/testing-connection-to-cloud-sql-instance-with-a-mysql-client-from-vm-instance):

```
List<String> names = ....for (String name : names) {   // Do something   names.remove(name).}
```

As an addendum, is it legal to remove [items](https://www.mindstick.com/forum/33812/getting-number-of-items-selected-in-uicollectionview-in-ios) that have not been iterated over yet? For instance,

```
//Assume that the names list as duplicate entriesList<String> names = ....for (String name : names) {    // Do something    while (names.remove(name));}
```

## Replies

### Reply by Anonymous User

To safely remove from a collection while iterating over it you should use an Iterator.\
For example:

```
List<String> names = ....Iterator<String> i = names.iterator();while (i.hasNext()) {   String s = i.next(); // must be called before you can call i.remove()   // Do something   i.remove();}
```

From the Java Documentation :\
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.Perhaps what is unclear to many novices is the fact that iterating over a list using the for/[foreach](https://www.mindstick.com/forum/33870/how-parallel-foreach-works-internally) constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here


---

Original Source: https://www.mindstick.com/forum/33436/calling-remove-in-foreach-loop-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
