To remove elements from a list based on a condition in Java using `java.util.ArrayList`, you can iterate through the list and remove elements that meet the condition.
In this example,
numbers
with some elements.remove
method.import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
int threshold = 3;
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int number = iterator.next();
if (number > threshold) {
iterator.remove();
}
}
System.out.println("Modified list after removing elements greater than " + threshold + ": " + numbers);
}
}
Modified list after removing elements greater than 3: [1, 2, 3]
In this example,
names
with some elements.Condition
with a method test
that defines the condition.remove
method.import java.util.ArrayList;
import java.util.Iterator;
interface Condition<T> {
boolean test(T element);
}
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("John");
names.add("Alice");
names.add("Michael");
names.add("Emma");
int maxLength = 5;
Condition<String> isLongName = element -> element.length() > maxLength;
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (isLongName.test(name)) {
iterator.remove();
}
}
System.out.println("Modified list after removing long names: " + names);
}
}
Modified list after removing long names: [John, Alice, Emma]
In this tutorial, we learned How to Remove Element from List based on a Condition in Java language with well detailed examples.