Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
Next article icon

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

Last Updated : 10 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report

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  




// Java code to demonstrate the working
// of peekFirst() in LinkedList
import java.util.*;
public class LinkedPeek2 {
  
public static void main(String[] args)
    {
        // declaring a LinkedList
        LinkedList list = new LinkedList();
  
        // adding  elements
        list.add("Geeks");
        list.add(4);
        list.add("Geeks");
        list.add("8");
  
        // printing the list
        System.out.println("The initial list is :" + list);
  
        // peek at the first element of the list
        // Prints 1st element, "Geeks"
        System.out.println("First element of the list is : " + list.peekFirst());
    }
}
 
 

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  




// Java code to demonstrate the working
// of peekLast() in LinkedList
import java.util.*;
public class LinkedPeek3 {
  
public static void main(String[] args)
    {
        // declaring a LinkedList
        LinkedList list = new LinkedList();
  
        // adding  elements
        list.add("Geeks");
        list.add(4);
        list.add("Geeks");
        list.add(8);
  
        // printing the list
        System.out.println("The initial list is :" + list);
  
        // peek at the last element of the list
        // Prints last element, 8
        System.out.println("Last element of the list is : " + list.peekLast());
    }
}
 
 

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.




// Java code to demonstrate the application
// of peek()
import java.util.*;
public class LinkedPeekApp {
  
public static void main(String[] args)
    {
  
        // declaring a LinkedList
        LinkedList list = new LinkedList();
  
        // adding  elements in deck
        list.add(5);
        list.add(4);
        list.add("Jack");
        list.add(8);
        list.add("King");
  
        // printing the list
        System.out.println("The initial deck is :" + list);
  
        String d = "upper";
  
        System.out.println("The element chosen to peek is : " + d);
  
        if (d == "upper")
            System.out.println("The Upper element is : " + list.peekFirst());
        else
            System.out.println("The Lower element is : " + list.peekLast());
    }
}
 
 

Output :

  The initial deck is :[5, 4, Jack, 8, King]  The element chosen to peek is : upper  The Upper element is : 5  



Next Article
Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-Collections
  • Java-Functions
  • Java-Library
  • java-LinkedList
  • Linked Lists
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • LinkedList addFirst() Method in Java
    In Java, the addFirst() method of LinkedList, adds elements at the beginning of the list. All the existing elements moved one position to the right and the new element is placed at the beginning. Syntax of LinkedList addFirst() Method public void addFirst( E e) Parameters: E is the data type of elem
    1 min read
  • LinkedList addLast() Method in Java
    In Java, the addLast() method of the LinkedList class is used to add an element at the end of the list. Syntax of LinkedList addLast() Method void addLast( E e) Parameter: e is the element you want to add at the end of the list.Return type: This method does not return any value.Example: Here, we use
    1 min read
  • LinkedList clear() Method in Java
    In Java, the clear() is used to remove all the elements from a LinkedList. This method only clears all the element from the list and not deletes the list. After calling this method, the list will be empty. Syntax of LinkedList clear() Methodvoid clear() Parameters: This method does not accept any pa
    1 min read
  • LinkedList clone() Method in Java
    In Java, the clone() method of LinkedList, creates a shallow copy which means the structure is duplicated but the objects inside the list are shared between the original and the copied list. So, the cloned list will have the same elements as the original list. Syntax of Java LinkedList clone() Metho
    1 min read
  • LinkedList contains() Method in Java
    In Java, the contains() method of LinkedList is used to check whether an element is present in a LinkedList or not. It takes the element as a parameter and returns True if the element is present in the list. Syntax of Java LinkedList contains() Method boolean contains(Object element);Parameter: The
    2 min read
  • LinkedList descendingIterator() Method in Java
    In Java, the descendingIterator() method of LinkedList is used to return an iterator that allows to traverse the list in reverse order. Example 1: This example demonstrates how to use descendingIterator() method with Strings in a LinkedList. [GFGTABS] Java // Java program to use // descendingIterato
    3 min read
  • LinkedList element() Method in Java
    In Java, the element() method of the LinkedList class is used to retrieve the first element in the list without removing it. The first element of the LinkedList is known as the head. Example 1: Here, we use the element() method to retrieve the first element of the LinkedList of Integers, without rem
    2 min read
  • Java.util.LinkedList.get(), getFirst(), getLast() in Java
    In Java, the LinkedList class provides several methods for accessing the elements in the list. Here are the methods for getting the elements of a LinkedList: get(int index): This method returns the element at the specified position in the LinkedList. The index parameter is zero-based, so the first e
    5 min read
  • LinkedList getLast() Method in Java
    In Java, the getLast() method in the LinkedList class is used to retrieve the last element of the list. Example 1: Here, we use the getLast() method to retrieve the last element of the list. [GFGTABS] Java // Java Program to Demonstrate the // use of getLast() in LinkedList import java.util.LinkedLi
    2 min read
  • LinkedList indexOf() Method in Java
    In Java, the indexOf() method of the LinkedList class is used to find the index of the first occurrence of the specified element in the list. Syntax of LinkedList indexOf() Method public int indexOf(Object o); Parameter: This method takes an object "o" as an argument. Return type: It returns the ind
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences