In Java, you can remove objects from a collection or list using the remove() method of the Iterator interface.
The Iterator interface provides a way to iterate over a collection and perform various operations, including removing elements while iterating.
Here's an example that demonstrates how to use the remove() method:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RemoveFromListExample {
public static void main(String[] args) {
// Create a list
List fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
// Create an iterator for the list
Iterator iterator = fruits.iterator();
// Iterate over the list and remove objects
while (iterator.hasNext()) {
String fruit = iterator.next();
if (fruit.equals("Banana") || fruit.equals("Mango")) {
iterator.remove(); // Removes the current element from the list
}
}
// Print the updated list
System.out.println(fruits); // Output: [Apple, Orange]
}
}
In this example, we create a list of fruits and add several elements to it. Then, we obtain an iterator for the list using the iterator() method. Next, we iterate over the list using a while loop and the hasNext() and next() methods of the iterator.
Inside the loop, we check if the current fruit is either "Banana" or "Mango" and use the remove() method to remove it from the list. After the iteration is complete, we print the updated list to verify that the "Banana" and "Mango" elements have been removed.
Note that using the Iterator's remove() method is the recommended way to remove elements while iterating over a collection or list in Java, as it avoids potential concurrent modification issues.
No comments:
Post a Comment