EN
Java - remove items from ArrayList using Iterator
0
points
In this article, we would like to show you how to remove items from ArrayList using Iterator in Java.
Quick solution:
Iterator<String> myIterator = letters.iterator();
while (myIterator.hasNext()) {
if (myIterator.next() == "B") {
myIterator.remove();
}
}
String ArrayList example
In this example, we use Iterator to remove "B"
element from the letters
ArrayList.
package arraylistOperations;
import java.util.*;
public class Example {
public static void main(String[] args) {
List<String> letters = new ArrayList<>();
letters.add("A");
letters.add("B");
letters.add("C");
Iterator<String> myIterator = letters.iterator();
while (myIterator.hasNext()) {
if (myIterator.next() == "B") {
myIterator.remove();
}
}
System.out.println(letters);
}
}
Output:
[A, C]
Integer ArrayList example
In this example, we remove all items with a value less than 2
from the numbers
ArrayList using Iterator.
import java.util.*;
public class Example {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
Iterator<Integer> myIterator = numbers.iterator();
while (myIterator.hasNext()) {
if (myIterator.next() < 3) {
myIterator.remove();
}
}
System.out.println(numbers);
}
}
Output:
[3, 4]
Note:
You can achieve the same result using
Collection.removeIf()
method.numbers.removeIf(x -> x < 3);