如何在 Java 中从一个列表中移除多个元素?
列表提供了 removeAll() 方法,该方法移除由提供的集合组成的列表的所有元素。
boolean removeAll(Collection<?> c)
参数
c − 包含要从此列表中移除元素的集合。
返回
如果此列表因调用而更改,则为 True
引发
UnsupportedOperationException − 如果此列表不支持 removeAll 操作。
ClassCastException − 如果此列表中元素的类与指定的集合不兼容(可选)。
NullPointerException − 如果此列表包含 null 元素且指定的集合不允许 null 元素(可选),或如果指定的集合为 null。
示例
以下是显示 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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP