Java LinkedList getFirst() Method with Examples

In the previous article, we have discussed about Java LinkedList get() Method with Examples

In this article we are going to see the use of Java LinkedList getFirst() method along with suitable examples.

Java LinkedList getFirst() Method with Examples

This java.util.LinkedList.getFirst() method is used retrieve the element present in the first/Head position of LinkedList.

It returns the element, which is present in the head of the LinkedList.

Syntax:

LinkedListName.getFirst()

Where,

  • LinkedListName refers to the name of your LinkedList.

Let’s see different examples to understand it more clearly.

Example-1: Java LinkedList getFirst() Method – Example with String Type LinkedList

Approach:

  • Create a new LinkedList of type String.
  • Add string elements into the LinkedList using the add() method.
  • Display the LinkedList elements.
  • Now get head element from the LinkedList using getFirst( ) method.
  • Print the element.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create a LinkedList of string datatype
        LinkedList<String> l = new LinkedList<String>();
        // Adding some elements to the LinkedList
        l.add("Hello");
        l.add("this");
        l.add("is");
        l.add("an");
        l.add("example of getFirst() method");
        // Prints the LinkedList elements
        System.out.println("The elements of LinkedList are: "+l);
        // get head element from the LinkedList
       System.out.println("Element at first position is: " + l.getFirst());
    }
}
Output:

The elements of LinkedList are: [Hello, this, is, an, example of getFirst() method]
Element at first position is: Hello

Example-2: Java LinkedList getFirst() Method – Example with Integer Type LinkedList

Approach:

  • Create a new LinkedList of type Integer.
  • Add integer elements into the LinkedList using the add() method.
  • Display the LinkedList elements.
  • Now get head element from  the LinkedList using getFirst( ) method.
  • Print the element.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create a LinkedList of Integer datatype
        LinkedList<Integer> l = new LinkedList<Integer>();
        // Adding some elements to the LinkedList
        l.add(2);
        l.add(52);
        l.add(13);
        l.add(17);
        l.add(1);
        // Prints the LinkedList elements
        System.out.println("The elements of LinkedList are: "+l);
        // get head element from the LinkedList
       System.out.println("Element at first position is: " + l.getFirst());
    }
}
Output:

The elements of LinkedList are: [2, 52, 13, 17, 1]
Element at first position is: 2

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples.

Related Java Programs: