How to Iterate LinkedList in Java?
Last Updated :
07 Jan, 2021
LinkedList in java is basically a part of the collection framework present in java.util package. It is the implementation of the LinkedList data structure that stores elements in a non-contiguous manner inside the memory.
Five ways to iterate a LinkedList are:
- Using for loop
- Using while loop
- Using enhanced for loop
- Using Iterator
- Using forEach() method
Method 1: Using For Loop
Java
// Java program for iterating the LinkedList
// using For loop
import java.util.LinkedList;
public class GFG {
public static void main(String[] args)
{
// Creating a LinkedList of Integer type
LinkedList<Integer> linkedList = new LinkedList<>();
// Inserting some Integer values to our LinkedList
linkedList.add(40);
linkedList.add(44);
linkedList.add(80);
linkedList.add(9);
// LinkedList after insertions: [40, 44, 80, 9]
// Calling the function to iterate our LinkedList
iterateUsingForLoop(linkedList);
}
// Function to iterate the LinkedList using a simple for
// loop
public static void
iterateUsingForLoop(LinkedList<Integer> linkedList)
{
System.out.print(
"Iterating the LinkedList using a simple for loop : ");
for (int i = 0; i < linkedList.size(); i++) {
System.out.print(linkedList.get(i) + " ");
}
}
}
OutputIterating the LinkedList using a simple for loop : 40 44 80 9
Method 2: Using while Loop
We can iterate our LinkedList using a while loop in a very similar way as we did using a for loop.
Java
// Java program for iterating the LinkedList
// using while loop
import java.util.LinkedList;
public class GFG {
public static void main(String[] args) {
// Creating a LinkedList of Character type
LinkedList<Character> vowels = new LinkedList<>();
// Inserting some Character values to our LinkedList
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
// LinkedList after insertions: ['a', 'e', 'i', 'o', 'u']
// calling the function to iterate our LinkedList
iterateUsingWhileLoop(vowels);
}
// Function to iterate our LinkedList using while loop
public static void iterateUsingWhileLoop(LinkedList<Character> vowels){
System.out.print("Iterating the LinkedList using while loop : ");
int i=0;
while(i<vowels.size()){
System.out.print(vowels.get(i) + " ");
i++;
}
}
}
OutputIterating the LinkedList using while loop : a e i o u
Method 3: Using enhanced for loop
Using enhanced for loop we can sequentially iterate a LinkedList. The execution of the enhanced for loop ends after we visit all the elements. Let us see an example of iterating the LinkedList using the enhanced for loop.
Java
// Java program for iterating the LinkedList
// using Enhanced For loop
import java.util.LinkedList;
public class GFG {
public static void main(String[] args)
{
// Creating a LinkedList of String type
LinkedList<String> linkedList = new LinkedList<>();
// Inserting some String values to our LinkedList
linkedList.add("Geeks");
linkedList.add("for");
linkedList.add("Geeks");
// LinkedList after insertions: ["Geeks", "for",
// "Geeks]
// Calling the function to iterate our LinkedList
iterateUsingEnhancedForLoop(linkedList);
}
// Function to display LinkedList using Enhanced for
// loop
public static void iterateUsingEnhancedForLoop(LinkedList<String> linkedList)
{
System.out.print(
"Iterating the LinkedList using enhanced for loop : ");
for (String listElement : linkedList) {
System.out.print(listElement + " ");
}
}
}
OutputIterating the LinkedList using enhanced for loop : Geeks for Geeks
Method 4: Using Iterator
- To iterate the LinkedList using the iterator we first create an iterator to the current list and keep on printing the next element using the next() method until the next element exists inside the LinkedList.
- We check if the LinkedList contains the next element using the hasNext() method.
Java
// Java program for iterating the LinkedList
// using Iterator
import java.util.Iterator;
// Importing LinkedList class from
// java.util package
import java.util.LinkedList;
public class GFG {
public static void main(String[] args) {
// Creating a LinkedList of Integer Type
LinkedList<Integer> linkedList = new LinkedList<>();
// Inserting some Integer values to our LinkedList
linkedList.add(5);
linkedList.add(100);
linkedList.add(41);
linkedList.add(40);
linkedList.add(7);
// LinkedList after insertions : [5, 100, 41, 40, 7]
// Calling the function to iterate our LinkedList
iterateUsingIterator(linkedList);
}
// Function to iterate the Linked List using Iterator
public static void iterateUsingIterator(LinkedList<Integer> linkedList){
System.out.print("Iterating the LinkedList using Iterator : ");
// Creating an Iterator to our current LinkedList
Iterator it = linkedList.iterator();
// Inside the while loop we check if the next element
// exists or not if the next element exists then we print
// the next element and move to it otherwise we come out
// of the loop
// hasNext() method return boolean value
// It returns true when the next element
// exists otherwise returns false
while(it.hasNext()){
// next() return the next element in the iteration
System.out.print(it.next() + " ");
}
}
}
OutputIterating the LinkedList using Iterator : 5 100 41 40 7
Method 5: Using forEach() method
- forEach() method was introduced in Java8.
- It performs the specified task for each element of the Iterable until all elements have been processed or the action throws an exception.
Syntax:
public void forEach(Consumer<? super E> action)
Java
// Java program for iterating the LinkedList
// using For Each loop
import java.util.LinkedList;
public class GFG {
public static void main(String[] args)
{
// Creating a LinkedList of Integer Type
LinkedList<Integer> linkedList = new LinkedList<>();
// Inserting some Integer values to our LinkedList
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);
// LinkedList after insertions: [1, 2, 3, 4, 5]
// Calling the function to iterate our LinkedList
iterateUsingForEach(linkedList);
}
public static void
iterateUsingForEach(LinkedList<Integer> linkedList)
{
System.out.print(
"Iterating the LinkedList using for each function : ");
// Calling the forEach function to iterate through
// all the elements inside the Linked List
linkedList.forEach(
(element) -> System.out.print(element + " "));
}
}
OutputIterating the LinkedList using for each function : 1 2 3 4 5
Similar Reads
How to iterate LinkedHashMap in Java? LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. Th
2 min read
How to Sort a LinkedList in Java? A Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations.Sorting the nodes of a Singly Linked list in ascending order:Original ListSorted ListWe can sort the LinkedList by many sorting techniques:Selection SortInsertion sortQuick sortMerge sort Me
13 min read
Iterate a LinkedList in Reverse Order in Java For traversing a linked list in reverse order we can use Descending Iterator or List Iterator 1. Descending Iterator Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist.descendingIterator(); Returns: Descending Iterator returns the
2 min read
How to Iterate over a Queue in Java? Queue is a concept of Linear Data Structure that follows the concept of FIFO(First In First Out). Queues are majorly used to maintain the order of the elements to which they are added. In this article, we will learn to perform Queue Iteration in Java. Queue Iteration Program in JavaSyntax with Examp
1 min read
Convert Array to LinkedList in Java Array is contiguous memory allocation while LinkedList is a block of elements randomly placed in the memory which are linked together where a block is holding the address of another block in memory. Sometimes as per requirement or because of space issues in memory where there are bigger chunks of co
3 min read
How to Implement Generic LinkedList in Java? Linked List is Linear Data Structures that store values in nodes. As we do know here each Node possesses two properties namely the value of the node and link to the next node if present so. Linked List can not only be of Integer data type but String, boolean, Float, Character, etc. We can implement
8 min read
How to Iterate LinkedHashMap in Reverse Order in Java? The LinkedHashMap is used to maintain an order of elements inserted into it. It provides where the elements can be accessed in their insertion order. A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class. It contains only unique elements or m
6 min read
Convert HashMap to LinkedList in Java HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. LinkedList is a part of the Collection framework present in java.util package. This class is an implementa
2 min read
Convert a HashSet to a LinkedList in Java In Java, HashSet and LinkedList are linear data structures. These are majorly used in many cases. There may be some cases where we need to convert HashSet to LinkedList. So, in this article, we will see how to convert HashSet to LinkedList in Java. Java Program to Convert a HashSet to a LinkedList T
2 min read
Iterate List in Java using Loops In this article, we are going to see how to iterate through a List. In Java, a List is an interface of the Collection framework. List can be of various types such as ArrayList, Stack, LinkedList, and Vector. There are various ways to iterate through a java List but here we will only be discussing ou
7 min read