LinkedBlockingDeque drainTo() method in Java with Example

The drainTo(Collection col) method of LinkedBlockingDeque removes all available elements from this LinkedBlockingDeque and adds them to the given collection passed as a parameter.

drainTo(Collection<E> col)

The drainTo(Collection<E> col) method of LinkedBlockingDeque removes all of the elements from this deque and adds them to the given collection col. This is a more efficient way than repeatedly polling this deque.

There is also possibilities of failure encountered while attempting to add elements to collection c from the deque and due to that failure, elements are distributed between both collections when the associated exception is thrown. If a deque is tried to drainTo() to deque itself, then IllegalArgumentException will be thrown. If the specified collection is modified while the operation is in progress, the behaviour of this operation is undefined. So for using such methods, one needs to take care of this type of situation to overcome exceptions.

Syntax:

public int drainTo(Collection<? super E> col)

Parameter: This method accepts one parameter col which represents the collection to transfer elements from LinkedBlockingDeque.

Return Value: This method returns the number of elements drained to collection from deque.

Exception: This method throws following exceptions:

  • UnsupportedOperationException– if collection cannot able to add elements.
  • ClassCastException– if class of element stops method to add element to collection.
  • NullPointerException– if the collection is null
  • IllegalArgumentException– if arguments of the method prevents it from being added to the specified collection

Below programs illustrates drainTo() method of LinkedBlockingDeque class:

Program 1:

Below program has a LinkedBlockingDeque which stores Employee objects. There is an ArrayList which will store all employee objects from LinkedBlockingDeque. So drainTo() is used with LinkedBlockingDeque to pass all employee from deque to ArrayList.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program Demonstrate drainTo(Collection c)
// method of LinkedBlockingDeque.
  
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingDeque;
  
public class GFG {
  
    // create a Employee Object with
    // position and salary as an attribute
    public class Employee {
  
        public String name;
        public String position;
        public String salary;
        Employee(String name, String position, String salary)
        {
            this.name = name;
            this.position = position;
            this.salary = salary;
        }
        @Override
        public String toString()
        {
            return "Employee [name=" + name + ", position="
                + position + ", salary=" + salary + "]";
        }
    }
  
    // Main Method
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        gfg.containsMethodExample();
    }
  
    public void containsMethodExample()
    {
  
        // define capacity of LinkedBlockingDeque
        int capacity = 50;
  
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque<Employee> linkedDeque
            = new LinkedBlockingDeque<Employee>(capacity);
  
        // create a ArrayList to pass as parameter to drainTo()
        ArrayList<Employee> collection
            = new ArrayList<Employee>();
  
        // add Employee object to deque
        Employee emp1 = new Employee("Aman", "Analyst", "24000");
        Employee emp2 = new Employee("Sachin", "Developer", "39000");
        linkedDeque.add(emp1);
        linkedDeque.add(emp2);
  
        // printing Arraylist and deque
        System.out.println("Before drainTo():");
        System.out.println("LinkedBlockingDeque : \n"
                           + linkedDeque.toString());
        System.out.println("ArrayList : \n"
                           + collection);
  
        // Apply drainTo method and pass collection as parameter
        int response = linkedDeque.drainTo(collection);
  
        // print no of element passed
        System.out.println("\nNo of element passed: "
                           + response);
  
        // printing Arraylist and deque
        // after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("LinkedBlockingDeque : \n"
                           + linkedDeque.toString());
        System.out.println("ArrayList : \n"
                           + collection);
    }
}

chevron_right


Output:

Before drainTo():
LinkedBlockingDeque : 
[Employee [name=Aman, position=Analyst, salary=24000], Employee [name=Sachin, position=Developer, salary=39000]]
ArrayList : 
[]

No of element passed: 2

After drainTo():
LinkedBlockingDeque : 
[]
ArrayList : 
[Employee [name=Aman, position=Analyst, salary=24000], Employee [name=Sachin, position=Developer, salary=39000]]

Program 2: Program to show exception thrown by drainTo() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program Demonstrate
// drainTo(Collection C)
// method of LinkedBlockingDeque.
  
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingDeque;
  
public class GFG {
  
    public static void main(String[] args)
        throws InterruptedException
    {
        // define capacity of LinkedBlockingDeque
        int capacityOfDeque = 4;
  
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque<Integer> linkedDeque
            = new LinkedBlockingDeque<Integer>(capacityOfDeque);
  
        // add elements to deque
        linkedDeque.put(85461);
        linkedDeque.put(44648);
        linkedDeque.put(45654);
  
        // create a collection with null
        ArrayList<Integer> add = null;
  
        // try to drain null deque to collection
        try {
            linkedDeque.drainTo(add);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

chevron_right


Output:

Exception: java.lang.NullPointerException

drainTo(Collection<? super E> col, int maxElements)

The drainTo(Collection<? super E> col, int maxElements) used to transfer fixed number elements which is passed as integer in drainTo() to collection which is also passed as parameter to method. After transferring the elements, LinkedBlockingDeque has only those elements which are not transferred to collection. This function is same as above function with some limitations to transfer fixed no of element.

Syntax:

public int drainTo(Collection<E> col, int maxElements)

Parameter: The method accepts two parameters:

  • col– It represents the collection to transfer elements from LinkedBlockingDeque.
  • maxElements– This is of integer type and refers to the maximum number of elements to be transferred to the collection.

Return Value: The method returns the number of elements drained to collection from deque.

Exception: This method throws following exceptions:

  • UnsupportedOperationException – if collection cannot able to add elements.
  • ClassCastException -if class of element stops method to add element to collection.
  • NullPointerException – if the collection is null
  • IllegalArgumentException – if arguments of the method prevents it from being added to the specified collection

Below programs illustrates drainTo(Collection<? super E> col, int maxElements) method of LinkedBlockingDeque class

Program 1:

Below program has a LinkedBlockingDeque which stores Employee objects and there is a HashSet in which will store all employee objects from LinkedBlockingDeque. So drainTo() of LinkedBlockingDeque is used to pass some employee from deque to ArrayList. So no of element to be transferred is passed in method as parameter.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program  to demonstrate drainTo()
// method of LinkedBlockingDeque.
  
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
  
public class GFG {
  
    // create an Employee Object with
    // position and salary as attribute
    public class Employee {
  
        public String name;
        public String position;
        public String salary;
        Employee(String name, String position, String salary)
        {
            this.name = name;
            this.position = position;
            this.salary = salary;
        }
        @Override
        public String toString()
        {
            return "Employee [name=" + name + ", "
                + "position=" + position
                + ", salary=" + salary + "]";
        }
    }
  
    // Main Method
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        gfg.containsMethodExample();
    }
  
    public void containsMethodExample()
    {
  
        // define capacity of LinkedBlockingDeque
        int capacity = 10;
  
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque<Employee> linkedDeque
            = new LinkedBlockingDeque<Employee>(capacity);
  
        // create a HashSet to pass as parameter to drainTo()
        HashSet<Employee> collection
            = new HashSet<Employee>();
  
        // add Employee object to deque
        Employee emp1 = new Employee("Sachin",
                                     "Analyst",
                                     "40000");
        Employee emp2 = new Employee("Aman",
                                     "Developer",
                                     "69000");
        Employee emp3 = new Employee("Kajal",
                                     "Accountant",
                                     "39000");
  
        linkedDeque.add(emp1);
        linkedDeque.add(emp2);
        linkedDeque.add(emp3);
  
        // printing Arraylist and deque
        // before applying drainTo() method
        System.out.println("Before drainTo():");
  
        System.out.println("No of Elements in Deque is "
                           + linkedDeque.size());
  
        System.out.println("Elements in Deque is as follows");
  
        Iterator<Employee> listOfemp
            = linkedDeque.iterator();
        while (listOfemp.hasNext())
            System.out.println(listOfemp.next());
  
        System.out.println("No of Elements in HashSet is "
                           + collection.size());
        System.out.println("Elements in HashSet is as follows:");
        for (Employee emp : collection)
            System.out.println(emp);
  
        // Initialize no of lement passed to collection
        // using drainTo() method
        int noOfElement = 2;
  
        // Apply drainTo method
        // and pass collection as parameter
        int response
            = linkedDeque.drainTo(collection, noOfElement);
  
        // print no of element passed
        System.out.println("\nNo of element passed: "
                           + response);
  
        // printing Arraylist and deque
        // after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("No of Elements in Deque is "
                           + linkedDeque.size());
        System.out.println("Elements in Deque is as follows");
        listOfemp = linkedDeque.iterator();
        while (listOfemp.hasNext())
            System.out.println(listOfemp.next());
  
        System.out.println("No of Elements in HashSet is "
                           + collection.size());
        System.out.println("Elements in HashSet is as follows:");
        for (Employee emp : collection)
            System.out.println(emp);
    }
}

chevron_right


Output:

Before drainTo():
No of Elements in Deque is 3
Elements in Deque is as follows
Employee [name=Sachin, position=Analyst, salary=40000]
Employee [name=Aman, position=Developer, salary=69000]
Employee [name=Kajal, position=Accountant, salary=39000]
No of Elements in HashSet is 0
Elements in HashSet is as follows:

No of element passed: 2

After drainTo():
No of Elements in Deque is 1
Elements in Deque is as follows
Employee [name=Kajal, position=Accountant, salary=39000]
No of Elements in HashSet is 2
Elements in HashSet is as follows:
Employee [name=Sachin, position=Analyst, salary=40000]
Employee [name=Aman, position=Developer, salary=69000]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.