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


Java CopyOnWriteArrayList removeIf()用法及代码示例


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

用法:

public boolean removeIf (Predicate<E> filter)

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


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

异常:如果指定的谓词过滤器为null,则此方法将引发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<Integer> ArrLis 
            = new CopyOnWriteArrayList<Integer>(); 
  
        // 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<String> ArrLis 
            = new CopyOnWriteArrayList<String>(); 
  
        // 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.function.Predicate-



相关用法


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