VOOZH about

URL: https://www.geeksforgeeks.org/java/java-util-linkedlist-peek-peekfirst-peeklast-java/

⇱ Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java

Last Updated : 10 Dec, 2018
Linked list class offers the functionality to "look into" the first and last elements of the list and hence can be useful in cases where only the retrieval is required and not necessarily the deletion is required. Three functionalities are present and all are discussed in this article.   1. peek() : This method retrieves, but does not remove, the head (first element) of this list.
Declaration : 
 public E peek()
Return Value : 
 This method returns the head of this list, or null if this list is empty.
Output:
The initial list is :[Geeks, 4, Geeks, 8]
Head of the list : Geeks

2. peekFirst() : This method retrieves, but does not remove, the first element of this list, or returns null if this list is empty. This works similar to peek().
Declaration : 
 public E peekFirst()
Return Value : 
 This method returns the first element of this list, or null if this list is empty
Output:
The initial list is :[Geeks, 4, Geeks, 8]
First element of the list is : Geeks

3. peekLast() : This method retrieves, but does not remove, the last element of this list, or returns null if this list is empty.
Declaration
 public E peekLast()
Return Value
 This method returns the last element of this list, or null if this list is empty
Output:
The initial list is :[Geeks, 4, Geeks, 8]
Last element of the list is : 8

Practical Application : The practical application that can be thought of is that this can be used in potentially the game of cards where the individuals can peek the first or last element of the deck on asking which element they want to see. Code below explains the working.
Output :
The initial deck is :[5, 4, Jack, 8, King]
The element chosen to peek is : upper
The Upper element is : 5

Comment