📌  相关文章
📜  Java中的 CopyOnWriteArrayList removeIf() 方法及示例

📅  最后修改于: 2022-05-13 01:55:36.015000             🧑  作者: Mango

Java中的 CopyOnWriteArrayList removeIf() 方法及示例

CopyOnWriteArrayList 的removeIf()方法从这个 CopyOnWriteArrayList 中移除满足指定条件的元素。

句法:

public boolean removeIf (Predicate filter)

参数:此方法接受一个强制参数过滤器,该过滤器是谓词值,基于从该列表中删除的元素。

返回值:如果 CopyOnWriteArrayList 发生更改,此方法返回一个布尔值,例如 true。否则此方法返回 false。

异常:如果指定的谓词过滤器为空,则此方法抛出NullPointerException

下面的程序说明了 CopyOnWriteArrayList 类的 removeIf()函数:

// Java Program to illustrate the CopyOnWriteArrayList
// removeIf() method in Java
  
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of CopyOnWriteArrayList
        CopyOnWriteArrayList ArrLis
            = new CopyOnWriteArrayList();
  
        // Add elements
        ArrLis.add(2);
        ArrLis.add(3);
        ArrLis.add(4);
        ArrLis.add(7);
        ArrLis.add(6);
        ArrLis.add(9);
  
        // print CopyOnWriteArrayList
        System.out.println("CopyOnWriteArrayList: "
                           + ArrLis);
  
        // if a number in the List is
        // divisible by 3, then remove it
        ArrLis.removeIf(number -> number % 3 == 0);
  
        // print updated CopyOnWriteArrayList
        System.out.println("Updated CopyOnWriteArrayList: "
                           + ArrLis);
    }
}
输出:
CopyOnWriteArrayList: [2, 3, 4, 7, 6, 9]
Updated CopyOnWriteArrayList: [2, 4, 7]
// Java Program to illustrate the CopyOnWriteArrayList
// removeIf() method in Java
  
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of CopyOnWriteArrayList
        CopyOnWriteArrayList ArrLis
            = new CopyOnWriteArrayList();
  
        // Add elements
        ArrLis.add("GeeksforGeeks");
        ArrLis.add("GFG");
        ArrLis.add("Geeks");
        ArrLis.add("Gfg");
  
        // print CopyOnWriteArrayList
        System.out.println("CopyOnWriteArrayList: "
                           + ArrLis);
  
        try {
  
            // This will throw NullPointerException
            ArrLis.removeIf(null);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
CopyOnWriteArrayList: [GeeksforGeeks, GFG, Geeks, Gfg]
java.lang.NullPointerException

参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/concurrent/CopyOnWriteArrayList.html#removeIf-java.util。函数.谓词-