The Wayback Machine - https://web.archive.org/web/20240822105424/https://www.geeksforgeeks.org/java-program-to-get-elements-of-a-linkedlist/
Open In App

Java Program to Get Elements of a LinkedList

Last Updated : 27 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList.

1. We can use get(int variable) method to access an element from a specific index of LinkedList:

In the given example, we have used the get(i) method. Here, the method returns the element which is at the i th index.

Syntax:

LinkedList.get(int index)

Parameters: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList.

Return Value: The method returns the element present at the position specified by the parameter index.

Java




// Java program to get the elements of Linkedlist
  
import java.io.*;
import java.util.LinkedList;
class GFG {
    public static void main(String[] args)
    {
  
        // Creating LinkedList
        LinkedList<String> gfg = new LinkedList<String>();
  
        // Adding values
        gfg.add("GEEKS");
        gfg.add("FOR");
        gfg.add("GEEKS");
  
        System.out.println("LinkedList Elements : ");
  
        for (int i = 0; i < gfg.size(); i++) {
  
            // get(i) returns element present at index i
            System.out.println("Element at index " + i
                               + " is: " + gfg.get(i));
        }
    }
}


Output

LinkedList Elements : 
Element at index 0 is: GEEKS
Element at index 1 is: FOR
Element at index 2 is: GEEKS

2. We can use the iterator() method

  • To use this method we have to import java.util.Iterator package.
  • In this method, we can iterate over the LinkedList and then extract the element at the given index accordingly.

Java




// Java program to iterate over linkedlist
// to extract elements of linkedlist
  
import java.io.*;
import java.util.LinkedList;
import java.util.Iterator;
class GFG {
    public static void main(String[] args)
    {
  
        LinkedList<String> gfg = new LinkedList<String>();
  
        // Adding elements
        gfg.add("GEEKS");
        gfg.add("FOR");
        gfg.add("GEEKS");
  
        // Create an object of Iterator
        Iterator<String> i = gfg.iterator();
  
        System.out.print(
            "The elements of the input LinkedList: \n");
  
        int j = 0;
  
        // has.next() returns true if there is a next
        // element
        while (i.hasNext()) {
  
            System.out.print("The element at the index " + j
                             + " ");
  
            // next() returns the next element
            String str = i.next();
  
            System.out.print(str);
            System.out.print(" \n");
  
            ++j;
        }
    }
}


Output

The elements of the input LinkedList: 
The element at the index 0 GEEKS 
The element at the index 1 FOR 
The element at the index 2 GEEKS

3. We can use ListIterator() method.

  • ListIterator() is a subinterface of Iterator() method.
  • It provides us with the function to access the elements of a list.
  • It is bidirectional that means it allows us to iterate elements of a list in the both the direction.
  • To use this method we have to import java.util.ListIterator.

Java




// Java program to iterate over the
// linkedlist using listIterator()
  
import java.io.*;
import java.util.LinkedList;
import java.util.ListIterator;
  
class GFG {
    public static void main(String[] args)
    {
  
        LinkedList<String> gfg = new LinkedList<String>();
  
        // Adding elements
        gfg.add("GEEKS");
        gfg.add("FOR");
        gfg.add("GEEKS");
  
        // Create an object of ListIterator
        ListIterator<String> li = gfg.listIterator();
  
        System.out.print(
            "The elements of the LinkedList: \n");
  
        // hasNext() returns true if there is next element
        int j = 0;
  
        while (li.hasNext()) {
  
            // next() returns the next element
            System.out.print("The element at the index " + j
                             + " ");
  
            System.out.print(li.next());
  
            System.out.print("\n");
  
            ++j;
        }
        --j;
  
        // Now to show that ListIterator() can traverse in
        // both the direction
        System.out.print(
            "\nThe elements of the LinkedList in Reverse order: \n");
  
        // hasprevious() checks if there is a previous
        // element
        while (li.hasPrevious()) {
  
            System.out.print("The element at the index " + j
                             + " ");
  
            // previous() returns the previous element
            System.out.print(li.previous());
            System.out.print("\n");
  
            --j;
        }
    }
}


Output

The elements of the LinkedList: 
The element at the index 0 GEEKS
The element at the index 1 FOR
The element at the index 2 GEEKS

The elements of the LinkedList in Reverse order: 
The element at the index 2 GEEKS
The element at the index 1 FOR
The element at the index 0 GEEKS


Similar Reads

Java.util.LinkedList.get(), getFirst(), getLast() in Java
In Java, the LinkedList class provides several methods for accessing the elements in the list. Here are the methods for getting the elements of a LinkedList: get(int index): This method returns the element at the specified position in the LinkedList. The index parameter is zero-based, so the first element has an index of 0.getFirst(): This method r
5 min read
LinkedList get() Method in Java
The Java.util.LinkedList.get() method is used to fetch or retrieve an element at a specific index from a LinkedList. Syntax: LinkedList.get(int index) Parameters: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList. Return Value: The method returns the element present at
1 min read
How to Get Sublist of LinkedList in Java?
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. Given a list of elements present in a Li
3 min read
How to Remove Duplicate Elements From Java LinkedList?
Linked List is a part of the Collection in java.util package. LinkedList class is an implementation of the LinkedList data structure it is a linear data structure. In LinkedList due to the dynamical allocation of memory, insertions and deletions are easy processes. For removing duplicates from Example: Initial composition : 7 2 3 3 2 7 6 2 After re
4 min read
How to Swap Two Elements in a LinkedList in Java?
Given a Linked List, the task is to swap two elements without disturbing their links. There are multiple ways to swap. Elements can be swapped using by swapping the elements inside the nodes, and by swapping the complete nodes. Example: Input :- 10-&gt;11-&gt;12-&gt;13-&gt;14-&gt;15 element1 = 11 element2 = 14 Output :- 10-&gt;14-&gt;12-&gt;13-&gt;
4 min read
How to Shuffle Elements in LinkedList in Java?
LinkedList is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers an
4 min read
Remove First and Last Elements from LinkedList in Java
The Java.util.LinkedList.removeFirst() method is used to remove the first element from the LinkedList. The Java.util.LinkedList.removeLast() method is used to remove the last element from the LinkedList. Both the methods also returns the element after removing it. 1. removeFirst() Syntax: LinkedList.removeFirst() Parameters: This function does not
2 min read
Java Program to Convert ArrayList to LinkedList
Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5] ArrayList - An ArrayList is a part of the collect
6 min read
Java Program to Sort LinkedList using Comparable
In Java, LinkedList is a part of the collection framework provided in java.util package. LinkedList is a linear data structure where all the elements are unsorted in contiguous memory locations. The advantage of LinkedList is it is dynamic and easy to insert and delete any element. We can not access any node of LinkedList directly we need to start
5 min read
Java Program to Implement LinkedList API
Linked List is a part of the Collection framework That is present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure in which the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. What is a Linked List API? Li
10 min read
Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
Linked list class offers the functionality to "look into" the first and last elements of the list and hence can be useful in cases where only the retrieval is required and not necessarily the deletion is required. Three functionalities are present and all are discussed in this article. 1. peek() : This method retrieves, but does not remove, the hea
4 min read
Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
Linked list also has a function that does the work of flexible addition of elements and helps addition both at front and back of the list, these functions literally "offer" the facility and named offer(). Three types are available and are discussed in this very article below. 1. offer(E e) : This method adds the specified element as the tail (last
4 min read
Java.util.LinkedList.indexOf(), lastIndexof() in Java
Linked list library also offers to depict the first and last index of element that has to be found using the indexOf() and lastIndexOf() functions respectively. They offer a variety as the direct access is not available in the conventionally made linked list, hence knowledge of it is useful. 1. indexOf(Object o) : This method returns the index of t
4 min read
Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
Java's Linked list class offers a function that allows a "Queue Based" working called poll(). This function not only returns deletes the first element, but also displays them while being deleted and hence can have a lot of usage in daily life problems and competitive programming as well. There are 3 variants of poll(), all three are discussed in th
4 min read
ArrayList vs LinkedList in Java
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to
5 min read
LinkedList removeFirst() Method in Java
In Java, the LinkedList class provides the removeFirst() method to remove and return the first element of the list. If the list is empty, the method throws a NoSuchElementException. Sure, here is an example of using the removeFirst() method in Java, with the full code and output: Java Code import java.util.LinkedList; public class Example { public
3 min read
LinkedList add() Method in Java With Examples
LinkedList is a class implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. As we all know that class contains various methods so do here we will be discussing and implementing add() method t
3 min read
LinkedList getFirst() Method in Java
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The Java.util.LinkedList.getFirst() meth
2 min read
LinkedList getLast() Method in Java
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and. The Java.util.LinkedList.getLast() method is used to
2 min read
LinkedList clear() Method in Java
The Java.util.LinkedList.clear() method is used to remove all the elements from a linked list. Using the clear() method only clears all the element from the list and not deletes the list. In other words we can say that the clear() method is used to only empty an existing LinkedList. Syntax: void clear() Parameters: This function does not accept any
1 min read
LinkedList addFirst() Method in Java
The java.util.LinkedList.addFirst() method in Java is used to insert a specific element at the beginning of a LinkedList. Syntax: void addFirst(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at beginning of the list. Return Value: This me
1 min read
LinkedList addLast() Method in Java
The java.util.LinkedList.addLast() method in Java is used to insert a specific element at the end of a LinkedList.Syntax: void addLast(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at end of the list.Return Value: This method does not re
1 min read
LinkedList addAll() Method in Java
java.util.LinkedList.addAll(Collection C): This method is used to append all of the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator. Syntax: boolean addAll(Collection C) Parameters: The parameter C is a collection of ArrayList. It is the collectio
3 min read
LinkedList set() Method in Java
The Java.util.LinkedList.set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method. Syntax: LinkedList.set(int index, Object element)Parameters: T
3 min read
LinkedList remove() Method in Java
LinkedList as we all know is a way of storing data that contains sets of nodes where each node contains data and address part where address part is responsible for linking of nodes and hence forming a List over which now we can perform operations. Now here we want to remove a node/s using the remove() method of LinkedList class only. Illustration:
4 min read
LinkedList removeLast() Method in Java
In Java, the LinkedList class provides the removeLast() method to remove and return the last element of the list. If the list is empty, the method throws a NoSuchElementException. Example: Java Code import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;();
2 min read
LinkedList size() Method in Java
The Java.util.LinkedList.size() method is used to get the size of the Linked list or the number of elements present in the linked list. Syntax: LinkedList.size()Parameters: This method does not take any parameter. Return Value: This method returns the size or the number of elements present in the LinkedList. Below program illustrates the Java.util.
2 min read
LinkedList indexOf() method in Java
The Java.util.LinkedList.indexOf(Object element) method is used to check and find the occurrence of a particular element in the list. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the list does not contain the element. Syntax: LinkedList.indexOf(Object element) Parameters: Th
2 min read
LinkedList lastIndexOf() Method in Java with Examples
The lastIndexOf(Object element) method of LinkedList class present inside java.util package is used to check and find the occurrence of a particular element in the list. If the element is present in the list then the lastIndexOf() method returns the index of the last occurrence of the element otherwise it returns -1. This method is used to find the
2 min read
LinkedList contains() Method in Java
The Java.util.LinkedList.contains() method is used to check whether an element is present in a LinkedList or not. It takes the element as a parameter and returns True if the element is present in the list. Syntax: LinkedList.contains(Object element) Parameters: The parameter element is of type LinkedList. This parameter refers to the element whose
2 min read
three90RightbarBannerImg