The retainAll() method of java.util.concurrent.LinkedTransferQueue is an in-built function in Java which is used to retain all the elements in this queue which are common to both i.e. the specified collection and this queue. All other elements which are not common are removed from this queue.
Syntax:
public boolean retainAll(Collection C)
Parameters: This method takes the parameter C which is the collection containing elements to be retained in the queue.
Returns: The method returns a boolean value true if the queue is changed at all as a result of the call else false.
Exceptions: This method throws following exceptions:
- ClassCastException: If the class of an element of this Queue is incompatible with the Passed collection.
- NullPointerException: If the specified collection is Null.
Below program illustrates the retainAll() 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( 3 );
LTQ.add( 6 );
LTQ.add( 10 );
LTQ.add( 125 );
LTQ.add( 205 );
System.out.println( "Linked Transfer Queue : "
+ LTQ);
ArrayList<Integer> arraylist
= new ArrayList<Integer>();
arraylist.add( 10 );
arraylist.add( 100 );
arraylist.add( 125 );
System.out.println( "ArrayList to be retained : "
+ arraylist);
LTQ.retainAll(arraylist);
System.out.println( "Linked Transfer Queue "
+ "after retaining ArrayList : "
+ LTQ);
}
}
|
Output:
Linked Transfer Queue : [3, 6, 10, 125, 205]
ArrayList to be retained : [10, 100, 125]
Linked Transfer Queue after retaining ArrayList : [10, 125]
Program 2:
import java.util.concurrent.LinkedTransferQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
LinkedTransferQueue<String> LTQ
= new LinkedTransferQueue<String>();
LTQ.add( "GeeksforGeeks" );
LTQ.add( "Geek" );
LTQ.add( "Gfg" );
LTQ.add( "Computer" );
LTQ.add( "Science" );
System.out.println( "Linked Transfer Queue : "
+ LTQ);
ArrayList<String> arraylist
= new ArrayList<String>();
arraylist.add( "Gfg" );
arraylist.add( "Science" );
arraylist.add( "Computer" );
System.out.println( "ArrayList to be retained : "
+ arraylist);
LTQ.retainAll(arraylist);
System.out.println( "Linked Transfer Queue "
+ "after retaining ArrayList : "
+ LTQ);
}
}
|
Output:
Linked Transfer Queue : [GeeksforGeeks, Geek, Gfg, Computer, Science]
ArrayList to be retained : [Gfg, Science, Computer]
Linked Transfer Queue after retaining ArrayList : [Gfg, Computer, Science]
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/LinkedTransferQueue.html#retainAll-java.util.Collection-