Java peek(), peekFirst() and peekLast() explanation with examples

Introduction :

Using LinkedList class, we can create one linked list in Java. This class provides a lot of different methods to operate on the elements of the linked list. In this tutorial, we will check three inbuilt methods peek(), peekFirst() and peekLast() of the LinkedList class.

These methods are used to read the first and the last element of a linked list without removing that element. Let me show you these methods one by one :

peek() :

peek() method is used to retrieve the first or the head element of a linked list. It doesn’t remove that element from the list. If the list is empty, it returns null.

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
        LinkedList<integer> firstList = new LinkedList<>();

        firstList.add(1);
        firstList.add(2);
        firstList.add(3);
        firstList.add(4);
        firstList.add(5);

        System.out.println("Original list : " + firstList);

        System.out.println("Result of Peek() : " + firstList.peek());

    }
}

If you run the above program, it will give the below output :

Original list : [1, 2, 3, 4, 5]
Result of Peek() : 1

peekFirst() :

peekFirst() is used to get the first element of a linked list. It returns null if the list is empty.

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
        LinkedList<integer> firstList = new LinkedList<>();

        firstList.add(1);
        firstList.add(2);
        firstList.add(3);
        firstList.add(4);
        firstList.add(5);

        System.out.println("Original list : " + firstList);

        System.out.println("Result of Peek() : " + firstList.peekFirst());

    }
}

It will print :

Original list : [1, 2, 3, 4, 5]
Result of Peek() : 1

peekLast() :

peekLast() is used to get the last element of a list like below :

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
        LinkedList<integer> firstList = new LinkedList<>();

        firstList.add(1);
        firstList.add(2);
        firstList.add(3);
        firstList.add(4);
        firstList.add(5);

        System.out.println("Original list : " + firstList);

        System.out.println("Result of Peek() : " + firstList.peekLast());

    }
}

Output :

Original list : [1, 2, 3, 4, 5]
Result of Peek() : 5

Similar tutorials :