beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – LinkedList peek(), peekFirst() and peekLast() methods

By Chaitanya Singh | Filed Under: Java.util package

Description

public E peek(): Retrieves, but does not remove, the head (first element) of this list.

public E peekFirst(): Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.

public E peekLast(): Retrieves, but does not remove, the last element of this list, or returns null if this list is empty.

Example

import java.util.LinkedList;
class LinkedListPeekDemo{

  public static void main(String[] args) {

     // Create a LinkedList of Strings
     LinkedList<String> list = new LinkedList<String>();

     // Add few Elements
     list.add("Element1");
     list.add("Element2");
     list.add("Element3");
     list.add("Element4");

     // Display LinkList elements
     System.out.println("LinkedList before: "+list);

     //peek()
     System.out.println(list.peek());
 
     //peekFirst()
     System.out.println(list.peekFirst());
 
     //peekLast()
     System.out.println(list.peekLast());

     // Should be same as peek methods does not remove
     System.out.println("LinkedList after: "+list);
  }
}

Output:

LinkedList before: [Element1, Element2, Element3, Element4]
Element1
Element1
Element4
LinkedList after: [Element1, Element2, Element3, Element4]

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap