Java LinkedList peekLast() Method Example

We already know that peekFirst() method of java.util.LinkedList class will return the first element of the list and will not remove the element from the list whereas peekLast() method will return the last element of the list and will not remove the element from the list. 


public E peekLast() 

Retrieves the tail (last element) of this list and will return null if the list is empty


The following example shows the usage of peekLast() method.

import java.util.LinkedList;

public class PeekLastMethodLinkedListExample {
	public static void main(String args[])
	// Create LinkedList object
        LinkedList list1 = new LinkedList();
        //adding elements to list1
        list1.add("String 1");
        list1.add("String 2");
        list1.add("String 3");
        list1.add("String 4");
        //Getting the tail of the LinkedList
      	System.out.println("Last element of the list is : "+list1.peekLast());


Last element of the list is : String 4

Leave a Reply

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