Java list removeAll()方法及实例

Java list removeAll()方法及实例

该方法用于从指定的列表中移除集合中存在的所有元素。

语法

boolean removeAll(Collection c)

参数: 该方法只有一个参数,就是要从给定的列表中删除哪些元素的集合。

返回: 如果元素被移除并且列表发生变化,该方法返回True。

下面的程序显示了这个方法的实现。

程序1:

// Java code to show the implementation of
// removeAll method in list interface
import java.util.*;
public class GfG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Initializing a list of type Linkedlist
        List<Integer> l = new LinkedList<>();
        l.add(10);
        l.add(30);
        l.add(50);
        l.add(70);
        l.add(90);
        System.out.println(l);
  
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(30);
        arr.add(50);
        l.removeAll(arr);
  
        System.out.println(l);
    }
}

输出。

[10, 30, 50, 70, 90]
[10, 70, 90]

程序2: 下面是使用Linkedlist实现list.removeAll()的代码。

// Java code to show the implementation of
// removeAll method in list interface
import java.util.*;
public class GfG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Initializing a list of type Linkedlist
        List<String> l = new LinkedList<>();
        l.add("10");
        l.add("30");
        l.add("50");
        l.add("70");
        l.add("90");
        System.out.println(l);
  
        ArrayList<String> arr = new ArrayList<>();
        arr.add("30");
        arr.add("50");
        l.removeAll(arr);
  
        System.out.println(l);
    }
}

输出。

[10, 30, 50, 70, 90]
[10, 70, 90]

参考资料:
Oracle文档

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程