This method returns the element from the head position of the underlying deque but, it does not delete that element. The element( ) method is different from this method only as peek() method returns 'null' if the queue is empty whereas element( ) method displays 'NoSuchElementException' exception.� This method is equivalent to the peekFirst() method.
peek() method of BlockingDeque Interface in Java.
In this section we will discuss how can peek() method be implemented in BlockingDeque interface.
Syntax
E peek( )
This method finds the head element from the deque or, returns 'null' if deque is empty.
This method returns the element from the head position of the underlying deque but, it does not delete that element. The element( ) method is different from this method only as peek() method returns 'null' if the queue is empty whereas element( ) method displays 'NoSuchElementException' exception. This method is equivalent to the peekFirst() method.
Parameter description
This method has no parameter
Example of peek( ) method
In this example we will show you, how does peek( ) method work in BlockingDeque interface. This example will help you to understand how can you retrieve the head element of the underlying deque.
package devmanuals.com; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; class Peek implements Runnable { BlockingDeque<Integer> bdq; public Peek(BlockingDeque<Integer> bdq) { this.bdq = bdq; } public void run() { System.out.println("Elements of deque are : "); int i; boolean bol = false; for (i = 0; i < 5; i++) { bdq.add(i); } System.out.println(bdq); System.out.println("Size of deque = " + bdq.size()); try { Thread.sleep(500); System.out.println("The first element of deque is = "); Thread.sleep(1000); Integer obj = bdq.peek(); System.out.println(obj); bol = bdq.contains(obj); System.out.println("The element " + obj+ " is still present into the deque? "); Thread.sleep(1000); System.out.println(bol); System.out.println("Now removed all the elements from the deque"); bdq.clear(); System.out.println("Therefore the deque is "+bdq+" empty"); System.out.println("Therefore first element of deque is : "); Integer obj1= bdq.peek();//call of this method will return 'null' Thread.sleep(2000); System.out.println(obj1); } catch (InterruptedException e) { e.printStackTrace(); } } } public class BdqPeek { public static void main(String[] args) { BlockingDeque<Integer> bdq = new LinkedBlockingDeque<Integer>(); Runnable a = new Peek(bdq); new Thread(a).start(); } }
Output :
Elements of deque are : [0, 1, 2, 3, 4] Size of deque = 5 The first element of deque is = 0 The element 0 is still present into the deque? true Now removed all the elements from the deque Therefore the deque is [] empty Therefore first element of deque is : null |
[ 0 ] Comments