getFirst() method

getFirst() method: This Java stream get First method employs to get the first element from LinkedList in Java. It returns the object.

E getFirst();

Where, E represents the type of elements in LinkedList.
throws NoSuchElementException 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 index 1
		System.out.println("Element present at first position is = 
                "+listOfNames.getFirst());
	}
}

Output: Element present at first position is = JAVA

Leave a Comment