LinkedTransferQueue removeIf() method in Java with Examples
The removeIf() method of java.util.concurrent.LinkedTransferQueue is an in-built function is Java which is used to remove all of the elements of this queue that satisfies a given predicate filter which is passed as a parameter to the method.
Syntax:
public boolean removeIf(Predicate filter)
Parameters: This method takes a parameter filter which represents a predicate which defines the filtering criteria for elements to be removed.
Return Value: This method returns a boolean value depicting if some the specified element has been removed. It returns True if the predicate returns true and the elements have been removed.
Exceptions: This method throws NullPointerException if the specified filter is null.
Below program illustrates the removeIf() function of LinkedTransferQueue class :
Program 1:
import java.util.concurrent.LinkedTransferQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
LinkedTransferQueue<Integer> LTQ
= new LinkedTransferQueue<Integer>();
LTQ.add( 6 );
LTQ.add( 3 );
LTQ.add( 5 );
LTQ.add( 15 );
LTQ.add( 20 );
System.out.println( "Linked Transfer Queue initially: "
+ LTQ);
if (LTQ.removeIf(n -> (n % 3 == 0 )))
System.out.println( "Multiples of 3 removed." );
else
System.out.println( "No element removed." );
System.out.println( "Current Linked Transfer Queue: "
+ LTQ);
}
}
|
Output:
Linked Transfer Queue initially: [6, 3, 5, 15, 20]
Multiples of 3 removed.
Current Linked Transfer Queue: [5, 20]
Program 2: To demonstrate NullPointerException
import java.util.concurrent.LinkedTransferQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
LinkedTransferQueue<Integer> LTQ
= new LinkedTransferQueue<Integer>();
LTQ.add( 6 );
LTQ.add( 3 );
LTQ.add( 5 );
LTQ.add( 15 );
LTQ.add( 20 );
System.out.println( "Linked Transfer Queue initially: "
+ LTQ);
try {
System.out.println( "Trying to remove null." );
LTQ.removeIf( null );
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
Linked Transfer Queue initially: [6, 3, 5, 15, 20]
Trying to remove null.
java.lang.NullPointerException
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/LinkedTransferQueue.html#removeIf(java.util.function.Predicate)
Last Updated :
08 Mar, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...