How to Retrieve Elements From LinkedList in Java

Java LinkedList Examples


The following example shows:
  • How to get the first element in the LinkedList.
  • How to get the last element in the LinkedList.
  • How to get the element at a given index in the LinkedList.

How to Retrieve Elements From LinkedList in Java

package com.javaguides.collections.linkedlistexamples;

import java.util.LinkedList;

public class RetrieveLinkedListElementsExample {
    public static void main(String[] args) {
     // Creating a LinkedList
        LinkedList<String> fruits = new LinkedList<>();
        
     // Adding new elements to the end of the LinkedList using add() method.
     fruits.add("Banana");
     fruits.add("Apple");
     fruits.add("mango");
     fruits.add("Pinaple");

        // Getting the first element in the LinkedList using getFirst()
     String firstElement = fruits.getFirst();
        System.out.println("First Fruit in List : " + firstElement);

        // Getting the last element in the LinkedList using getLast()
        String lastElement = fruits.getLast();
        System.out.println("Last fruit in List : " + lastElement);

        // Getting the element at a given position in the LinkedList
        String pinapleFruit = fruits.get(2);
        System.out.println("Stock Price on 3rd Day : " + pinapleFruit);
        
        System.out.println("Getting all the elements -> ");
        // Getting all the elements
        fruits.forEach( element -> {
         System.out.println(element);
        });
    }
}
Output:
First Fruit in List : Banana
Last fruit in List : Pinaple
Stock Price on 3rd Day : mango
Getting all the elements -> 
Banana
Apple
mango
Pinaple

Comments