The java.util.ArrayDeque.peek() method in Java is used to retrieve or fetch the element at the head of the Deque. The element retrieved does not get deleted or removed from the Queue instead the method just returns it. If no element is present in the deque then Null is returned.
Syntax:
Array_Deque.peek()
Parameters: The method does not take any parameter.
Return Value: The method returns the element at the head of the Deque.
Below programs illustrate the Java.util.ArrayDeque.peek() method:
Program 1:
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
ArrayDeque<String> de_que = new ArrayDeque<String>();
de_que.add( "Welcome" );
de_que.add( "To" );
de_que.add( "Geeks" );
de_que.add( "4" );
de_que.add( "Geeks" );
System.out.println( "Initial ArrayDeque: " + de_que);
System.out.println( "The element at head is: " +
de_que.peek());
System.out.println( "Final ArrayDeque: " + de_que);
}
}
|
Output:
Initial ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The element at head is: Welcome
Final ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
Program 2:
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
ArrayDeque<Integer> de_que = new ArrayDeque<Integer>();
de_que.add( 10 );
de_que.add( 15 );
de_que.add( 30 );
de_que.add( 20 );
de_que.add( 5 );
System.out.println( "Initial ArrayDeque: " + de_que);
System.out.println( "The element at head is: " +
de_que.peek());
System.out.println( "Final ArrayDeque: " + de_que);
}
}
|
Output:
Initial ArrayDeque: [10, 15, 30, 20, 5]
The element at head is: 10
Final ArrayDeque: [10, 15, 30, 20, 5]
Program 3: For an empty deque:
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
ArrayDeque<Integer> de_que = new ArrayDeque<Integer>();
System.out.println( "ArrayDeque: " + de_que);
System.out.println( "The element at head is: " + de_que.peek());
}
}
|
Output:
ArrayDeque: []
The element at head is: null
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
10 Dec, 2018
Like Article
Save Article