Java Program to Access elements from a LinkedList.

In the following example of Java program to access elements from a LinkedList :
Program :
Element at index 2: C++
Element at index 4: Ruby
Elements in the LinkedList:Java Python
C++
JavaScript
Ruby
PHP
Output :
In the above program, we first create a LinkedList object and add some elements to it using the add() method. To access an element from the linked list, we can use the get() method and pass the index of the element as the argument. We have accessed the elements at index 2 and index 4 in the linked list.

Alternatively, we can use a for-each loop to access all the elements in the linked list. In the for-each loop, we iterate over each element in the linked list and print it to the console.


Example 2 : Using listIterator() method :

We can also use the listIterator() method to iterate over the elements of a LinkedList. To use this method, we must import java.util.ListIterator package.
Program :
import java.util.LinkedList;
import java.util.ListIterator;

class Main {
    public static void main(String[] args) {
        LinkedList<String> languages= new LinkedList<>();

        // Add elements in LinkedList
        languages.add("HTML5");
        languages.add("CSS3");
        languages.add("Java");
        languages.add("Python");

        // Create an object of ListIterator
        ListIterator<String> listIterate = languages.listIterator();
        System.out.print("LinkedList: ");

        while(listIterate.hasNext()) {
            System.out.print(listIterate.next());
            System.out.print(", ");
        }

        // Iterate backward
        System.out.print("\nReverse LinkedList: ");

        while(listIterate.hasPrevious()) {
            System.out.print(listIterate.previous());
            System.out.print(", ");
        }
    }
}
Output :
LinkedList: HTML5, CSS3, Java, Python, 
Reverse LinkedList: Python, Java, CSS3, HTML5, 
Here,

hasNext() - returns true if there is a next element

next() - returns the next element

hasPrevious() - returns true if there exist previous elements

previous() - returns the previous element