如何在 Java 中从列表中删除多个元素?
javaobject oriented programmingprogramming更新于 2024/12/31 7:08:17
List 提供 removeAll() 方法来删除列表中所有属于所提供集合的元素。
boolean removeAll(Collection<?> c)
参数
c − 包含要从此列表中删除的元素的集合。
返回
如果此列表因调用而发生变化,则为 True
抛出
UnsupportedOperationException − 如果此列表不支持 removeAll 操作。
ClassCastException −如果此列表中元素的类与指定集合不兼容(可选)。
NullPointerException − 如果此列表包含空元素,并且指定集合不允许空元素(可选),或者指定集合为空。
示例
以下是显示 removeAll() 方法用法的示例 −
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
List<Integer> list1 = new ArrayList<>(Arrays.asList(6,7,8,9));
System.out.println("List: " + list);
list.removeAll(list1);
System.out.println("Updated List: " + list);
}
}
输出
这将产生以下结果 −
List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Updated List: [0, 1, 2, 3, 4, 5]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

