To remove a specific element from a list in Java using `java.util.ArrayList`, you can use the `remove` method.
In this example,
list
with some elements.remove
method of the list to remove the element if it is present.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
int elementToRemove = 3;
list.remove(Integer.valueOf(elementToRemove));
System.out.println("Modified list after removing " + elementToRemove + ": " + list);
}
}
Modified list after removing 3: [1, 2, 4, 5]
In this example,
list
with some elements.remove
method of the list to attempt to remove the element.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
int elementToRemove = 6;
list.remove(Integer.valueOf(elementToRemove));
System.out.println("Original list: " + list);
}
}
Original list: [1, 2, 3, 4, 5]
In this tutorial, we learned How to Remove Specific Element from a List in Java language with well detailed examples.