Calling remove in foreach loop in Java

If you want to remove elements from a collection while iterating over it using a for-each loop in Java, you must use an iterator instead of the looping construct. This is because the for-each loop is implemented using an iterator behind the scenes, and it does not provide a way to remove elements from the collection.

Here's an example of how you can use an iterator to remove elements from a collection while iterating over it:

import java.util.Iterator;
import java.util.List;

public class CollectionUtils {
  public static void removeEvenNumbers(List<Integer> numbers) {
    Iterator<Integer> iterator = numbers.iterator();
    while (iterator.hasNext()) {
      int number = iterator.next();
      if (number % 2 == 0) {
        iterator.remove(); // remove the even number
      }
    }
  }
}

This code defines a removeEvenNumbers method that takes a List of integers as an argument and removes all even numbers from the list using an iterator.

To use this method, you can simply call it and pass in your list as an argument:

List<Integer> numbers = ...; // initialize the list
CollectionUtils.removeEvenNumbers(numbers);

This will remove all even numbers from the list.

I hope this helps! Let me know if you have any questions.