How to remove an element from a list in Java?
To remove a specific element from a List in Java, you can use the `remove()` method. Here are a few ways to delete elements from a List.
Remove elements by their values.
List<String> list = new ArrayList<>();list.add("Apple");
list.add("Banana");
list.add("Orange");
list.remove("Banana"); // 通过元素值删除
System.out.println(list); // 输出: [Apple, Orange]
Remove elements by their index position.
List<String> list = new ArrayList<>();list.add("Apple");
list.add("Banana");
list.add("Orange");
list.remove(1); // 通过索引位置删除 (索引从0开始)
System.out.println(list); // 输出: [Apple, Orange]
3. Removing elements using iterators:
List<String> list = new ArrayList<>();list.add("Apple");
list.add("Banana");
list.add("Orange");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("Banana")) {
iterator.remove(); // 使用迭代器删除
}
}
System.out.println(list); // 输出: [Apple, Orange]
You can use any method to remove a specific element from the list. Just choose the method that suits your needs.