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

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

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

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

句法:

public boolean removeIf (Predicate filter)

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

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

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

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

方案一:

// Java Program Demonstrate removeIf()
// method of LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
        throws InterruptedException
    {
  
        // Create object of LinkedBlockingDeque
        LinkedBlockingDeque LBD
            = new LinkedBlockingDeque();
  
        // Add numbers to end of LinkedBlockingDeque
        LBD.add(7855642);
        LBD.add(35658786);
        LBD.add(5278367);
        LBD.add(74381793);
  
        // Print Deque
        System.out.println("Linked Blocking Deque: "
                           + LBD);
  
        // If a number in the List is
        // divisible by 3, then remove it
        LBD.removeIf(number -> number % 3 == 0);
  
        System.out.println("Linked Blocking Deque: "
                           + LBD);
    }
}
输出:
Linked Blocking Deque: [7855642, 35658786, 5278367, 74381793]
Linked Blocking Deque: [7855642, 5278367]

方案二:

// Java Program Demonstrate removeIf()
// method of LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
        throws InterruptedException
    {
  
        // Create object of LinkedBlockingDeque
        LinkedBlockingDeque LBD
            = new LinkedBlockingDeque();
  
        // Add numbers to end of LinkedBlockingDeque
        LBD.add(7855642);
        LBD.add(35658786);
        LBD.add(5278367);
        LBD.add(74381793);
  
        // Print Dequeue
        System.out.println("Linked Blocking Deque: "
                           + LBD);
  
        try {
            // if the predicate is null,
            // then it will throw NullPointerException
            LBD.removeIf(null);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Linked Blocking Deque: [7855642, 35658786, 5278367, 74381793]
java.lang.NullPointerException

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