peek() method: The peek in Java method uses to get the first element from LinkedList. It just Retrieves the element but does not remove it. It returns the object.
E peek();
Where, E represents the type of elements in LinkedList.
return null, if this LinkedList is empty.
import java.util.LinkedList; public class ExampleOfLinkedList { public static void main(String[] args) { LinkedList<String> listOfNames = new LinkedList<String>(); listOfNames.add("JAVA"); listOfNames.add("GOAL"); listOfNames.add("RAVI"); // It returns the element present at first position System.out.println("Element present at first position is = "+listOfNames.peek()); } }
Output: Element present at first position is = JAVA