In this section, we will learn what the LinkedList peek(), peekFirst(), and peekLast() methods are and how to use them in Java.
What is Java LinkedList peek() Method?
The Java LinkedList peek() method is used to get the first (head) element of a LinkedList object and returns that as a result.
Note: this method does not remove the element.
Java peek() Method Syntax:
public E peek()
peek() Method Parameters:
The method does not take an argument.
peek() Method Return Value:
The return value of this method is a copy of the first (head) element in the target LinkedList object.
Note: the value null returns if the target list object is empty.
peek() Method Exceptions:
The method does not throw an exception.
Example: using LinkedList peek() method
import java.util.LinkedList; class Main{ public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.offer("John"); list.offer("Omid"); list.offer("Jack"); list.offer("Ellen"); list.offer("Elon"); System.out.println(list.peek()); } }
Output:
John
What is Java LinkedList peekFirst() Method?
The Java LinkedList peekFirst() method is used to get the first (head) element of a LinkedList object and return that as a result.
Notes:
- This method does not remove the element.
- The method works the same as the peek() method.
Java peekFirst() Method Syntax:
public E peekFirst()
peekFirst() Method Parameters:
The method does not take an argument.
peekFirst() Method Return Value:
The return value of this method is a copy of the first element in the target LinkedList object.
Note: the value null returns if the target list object is empty.
peekFirst() Method Exceptions:
The method does not throw an exception.
Example: using LinkedList peekFirst() method
import java.util.LinkedList; class Main{ public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.offer("John"); list.offer("Omid"); list.offer("Jack"); list.offer("Ellen"); list.offer("Elon"); System.out.println(list.peekFirst()); } }
Output:
John
What is Java LinkedList peekLast() Method?
The Java LinkedList peekLast() method is used to get the last element of a LinkedList object and return that as a result.
Note: this method does not remove the element.
Java peekLast() Method Syntax:
public E peekLast()
peekLast() Method Parameters:
The method does not take an argument.
peekLast() Method Return Value:
The return value of this method is a copy of the last element in the target LinkedList object.
Note: the value null returns if the target list object is empty.
peekLast() Method Exceptions:
The method does not throw an exception.
Example: using LinkedList peekLast() method
import java.util.LinkedList; class Main{ public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.offer("John"); list.offer("Omid"); list.offer("Jack"); list.offer("Ellen"); list.offer("Elon"); System.out.println(list.peekLast()); } }
Output:
Elon