java中list的removeall方法如何使用

   2025-02-20 7770
核心提示:在Java中,List的removeAll方法用于从当前List中移除另一个Collection中包含的所有元素。该方法的使用方式如下:创建一个List对

在Java中,List的removeAll方法用于从当前List中移除另一个Collection中包含的所有元素。该方法的使用方式如下:

创建一个List对象:
List<Integer> list = new ArrayList<>();
初始化List对象:
list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);
创建一个Collection对象,该对象包含需要移除的元素:
Collection<Integer> collection = new ArrayList<>();collection.add(2);collection.add(4);collection.add(6);
使用removeAll方法将collection中的元素从list中移除:
list.removeAll(collection);
输出移除后的list:
System.out.println(list);

完整示例代码如下:

import java.util.ArrayList;import java.util.Collection;import java.util.List;public class Main {public static void main(String[] args) {List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);Collection<Integer> collection = new ArrayList<>();collection.add(2);collection.add(4);collection.add(6);list.removeAll(collection);System.out.println(list);}}

输出结果为:

[1, 3, 5]

可以看到,移除了list中与collection中相同的元素2和4,最终list中只剩下了1、3、5。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言