Java ArrayDeque Class: peek()Method
public E peek()
The peek() method is used to retrieve the head of the queue represented by a given deque.
This method is equivalent to peekFirst().
Package: java.util
Java Platform: Java SE 8
Syntax:
peek()
Return Value:
the head of the queue represented by this deque, or null if this deque is empty
Return Value Type: E - the type of elements held in this collection
Pictorial Presentation
Example: Java ArrayDeque Class: peek() Method
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
// Create an empty array deque
Deque<Integer> deque = new ArrayDeque<Integer>(8);
// Use add() method to add elements in the deque
deque.add(20);
deque.add(30);
deque.add(40);
deque.add(35);
// Print all the elements of the original deque
System.out.println("Elements of the original deque:");
for (Integer n : deque) {
System.out.println(n);
}
// this will retrieve head of the queue
int val = deque.peek();
System.out.println("Retrieved Element is " + val);
// Print all the elements available in deque
System.out.println("Elements of the deque:");
for (Integer n : deque) {
System.out.println(n);
}
}
}
Output:
Elements of the original deque: 20 30 40 35 Retrieved Element is 20 Elements of the deque: 20 30 40 35
Java Code Editor:
Previous:offerLast Method
Next:peekFirst Method
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-tutorial/util/arraydeque/java_arraydeque_peek.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics