當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。