当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Collection removeAll()用法及代码示例


removeAll()Java Collection 的方法从集合中删除作为函数参数给出的集合中包含的那些元素。

用法

boolean removeAll(Collection<?> c);

参数:

  • c 是包含从调用集合中删除的元素的集合。

返回类型:

它返回一个布尔值值。如果调用集合已被 removeAll() 方法修改,则返回 true,否则返回 false。

集合removeAll()方法示例

下面是上述方法的实现:

Java


// Java Program to demonstrate 
// Collection removeAll() method 
import java.io.*; 
import java.util.ArrayList; 
import java.util.Collection; 
import java.util.List; 
  
// Driver Class 
class Main { 
    // main function 
    public static void main(String[] args) 
    { 
        Collection<Integer> list1 = new ArrayList<>(); 
        list1.add(1); 
        list1.add(2); 
        list1.add(3); 
        list1.add(4); 
  
        System.out.println("Original List: " + list1); 
  
        // ArrayList 
        Collection<Integer> list2 = new ArrayList<>(); 
        list2.add(2); 
        list2.add(4); 
  
        System.out.println( 
            "List containing elements to be removed from the calling collection(list1): "
            + list2); 
  
        boolean isRemoved = list1.removeAll(list2); 
  
        System.out.println("Elements removed from List1: "
                           + isRemoved); 
        System.out.println("Modified list1 after deletion: "
                           + list1); 
    } 
}
输出
Original List: [1, 2, 3, 4]
List containing elements to be removed from the calling collection(list1): [2, 4]
Elements removed from List1: true
Modified list1 after deletion: [1, 3]

示例 2:

另一个例子,作为参数传递的集合不包含任何可以在原始集合中删除的元素。

Java


import java.io.*; 
import java.util.ArrayList; 
import java.util.List; 
  
// Driver Class 
class GFG { 
      // main function 
    public static void main(String[] args) 
    { 
          
        // Initiating list1 
        List<Integer> list1 = new ArrayList<Integer>(); 
        list1.add(1); 
        list1.add(2); 
        list1.add(3); 
        list1.add(4); 
  
        System.out.println("Original List: " + list1); 
  
          // Initiating list2 
        List<Integer> list2 = new ArrayList<Integer>(); 
        list2.add(7); 
        list2.add(8); 
  
        System.out.println( 
            "List containing elements to be removed from the calling collection(list1): "
            + list2); 
  
          // Using removeAll() method 
        boolean isRemoved = list1.removeAll(list2); 
  
        System.out.println("Elements removed from List1: "
                           + isRemoved); 
        System.out.println("Modified list1 after deletion: "
                           + list1); 
    } 
}
输出
Original List: [1, 2, 3, 4]
List containing elements to be removed from the calling collection(list1): [7, 8]
Elements removed from List1: false
Modified list1 after deletion: [1, 2, 3, 4]



相关用法


注:本文由纯净天空筛选整理自saswatdas121大神的英文原创作品 Java Collection removeAll() Method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。