LinkedList peekFirst() method with example in java
The peekFirst() method of LinkedList retrieves but does not remove the first element in this linked list. It returns null if the linked list is empty.
Syntax
Object peekFirst()
Parameters
It does not take any parameter
Return Value
It returns the first element in this linked-list or null if the linked-list is empty.
Program 1
import java.util.LinkedList; public class LinkedListPeekFirstExample { public static void main(String[] args) { LinkedListoddNumbers = new LinkedList(); oddNumbers.add(5); oddNumbers.add(7); oddNumbers.add(9); oddNumbers.add(11); System.out.println("Linked List elements: " + oddNumbers); System.out.println("First element in this linked-list: " + oddNumbers.peekFirst()); } }
Output
Linked List elements: [5, 7, 9, 11] First element in this linked-list: 5
Program 2
import java.util.LinkedList; public class LinkedListPeekFirstExample { public static void main(String[] args) { LinkedListoddNumbers = new LinkedList(); oddNumbers.add(5); oddNumbers.add(7); oddNumbers.add(9); oddNumbers.add(11); System.out.println("Linked List elements: " + oddNumbers); oddNumbers.clear(); System.out.println("Linked List elements after clear() call: " + oddNumbers); System.out.println("First element in this linked-list: " + oddNumbers.peekFirst()); } }
Output
Linked List elements: [5, 7, 9, 11] Linked List elements after clear() call: [] First element in this linked-list: null
0 Comments