How to Iterate LinkedList in Java?


The LinkedHashMap Class is similar to HashMap. But it has an additional feature in comparison to HashMap. The LinkedList class belongs to the java.util package.

A doubly linked list is how LinkedList stores its elements. Given that our operations typically include insertion and deletion, LinkedList is the best option.

The java.util package contains the LinkedList collection framework. It acts as an implementation of the non-contiguous LinkedList data structure, which saves elements in memory.

Methods Used

There are five main methods that you can use for iterating HashMap −

  • Using the for loop

  • Making use of a while loop

  • Using enhanced for loop or for-each loop

  • Employing Iterator

  • Making use of the forEach() method

Method 1: Iterating LinkedList by using for loop

A for loop is the easiest approach to iterate over the factors of a LinkedList in Java. To get the variety of elements inside the list, we use the size() approach. The elements will then be iterated over the usage of a for loop.

size()

The code creates a LinkedList object known as "list" and provides four factors to it: "Java," "c language," "Python," and "Ruby." It then iterates over the linked list with the usage of a for loop and prints each element.

Algorithm

  • Step 1 − Import the necessary class LinkedList from the java.util package.

  • Step 2 − Create a public class named LinkedListEx1 within the iterateLinkedList package.

  • Step 3 − Define the main method.

  • Step 4 − Declare and initialize an empty LinkedList object called list to store strings.

  • Step 5 − Addition of four components ("Java," "C Language," "Python," and "Ruby") to the list with the usage of the add method.

  • Step 6 − Begin traversing over the components of the linked list. You do it with the help of for loop.

  • Step 7 − Within each iteration, retrieve the element at the current index with the help of the get method. Then save it in the element variable.

  • Step 8 − Print the value of the element variable, which represents each string in the list.

Example

package iterateLinkedList; 
import java.util.LinkedList;

public class LinkedListEx1 {

   public static void main(String[] args) {
   
      // Generate a generic LinkedList object of string type.
      LinkedList<String> list = new LinkedList<String>(); // an empty list.

      // Adding elements in the list.
      list.add("Java");
      list.add("C Language");
      list.add("Python");
      list.add("Ruby");

      // Iterating linked list using for-each loop.
      System.out.println("For-each loop Method");
      for (String element : list) {
         System.out.println(element);
      }
   }
}

Output

For-each loop Method
Java
C Language
Python
Ruby

Method 2: Iterating with the help of a while loop

The while loop is the second way for iterating through entries of a linked list. It is effective for a small quantity of data in LinkedList.

get()

The code example generates a LinkedList referred to as "cities." Then comes the incorporation of four strings to it." It then iterates over the linked list with the help of a while loop and prints each element.

Algorithm

  • Step 1 − Create an empty LinkedList called "cities."

  • Step 2 − Add the strings "Bangalore," "Mumbai," "Kolkatta," and "Chennai" to the cities list.

  • Step 3 − Specify a counter variable, "num," with a default value of 0.

  • Step 4 − Enter a while loop that continues as long as the size of the cities list is greater than the value of "num."

  • Step 5 − Inside each iteration, retrieve the element at the current index (determined by "num") with the usage of the get method and print it.

  • Step 6 − Increase the value of "num" by 1.

  • Step 7 − Finish the loop and program.

Example

package iterateLinkedList;

import java.util.LinkedList;

public class Tutorialspoint {
   public static void main(String[] args) {
      // generate a LinkedList object of string type.
      LinkedList<String> cities = new LinkedList<String>();

      // Addition of elements of only string type.
      cities.add("Bangalore");
      cities.add("Mumbai");
      cities.add("Kolkatta");
      cities.add("Chennai");

      System.out.println("**Using While Loop for iteration of LinkedList **");
      int num = 0;
      while (cities.size() > num) {
         System.out.println(cities.get(num));
         num++;
      }
   }
}

Output

**Using While Loop for iteration of LinkedList **
Bangalore
Mumbai
Kolkatta
Chennai

Method 3: Iterate with the usage of enhanced for loop

Using a for-each loop or advanced for loop to iterate over a LinkedList in Java is an additional approach. In this function, we directly iterate through the LinkedList's elements using an advanced for loop.

for()

The code creates a LinkedList and adds three strings to it. It then uses an enhanced for loop to iterate over the elements of the LinkedList and prints them.

Algorithm

  • Step 1 − Import the required class LinkedList from the java.util package.

  • Step 2 − Create the public class Tutorialspoint.

  • Step 3 − Craft the main method.

  • Step 4 − Create a LinkedList object called linkedList to save strings.

  • Step 5 − Add the strings "Welcome," "to" and "Tutorialspoint" to the linked list with the help of the add method.

  • Step 6 − Call the method iterateUsingEnhancedForLoop and pass the linkedList as an argument.

  • Step 7 −Define the method iterateUsingEnhancedForLoop that takes a LinkedList of strings as a parameter.

  • Step 8 − Print the initial message "Iterating the LinkedList with the help of enhanced for loop: "

  • Step 9 − Using an enhanced for loop to iterate over each element (listElement) in the linkedList.

  • Step 10 − Inside each iteration, print the value of listElement followed by a space.

  • Step 11 − Close the loop and program.

Example

import java.util.LinkedList;

public class Tutorialspoint {
   public static void main(String[] args){

      LinkedList<String> linkedList = new LinkedList<>();

      linkedList.add("Welcome");
      linkedList.add("to");
      linkedList.add("Tutorialspoint");

      iterateUsingEnhancedForLoop(linkedList);
   }

   public static void iterateUsingEnhancedForLoop(LinkedList<String> linkedList){

      System.out.print("Iterating the LinkedList with the help of enhanced for loop : ");
      for (String listElement : linkedList) {
         System.out.print(listElement + " ");
      }
   }
}

Output

Iterating the LinkedList with the help of enhanced for loop : Welcome to Tutorialspoint

Method 4: Using iterator

Using an iterator is one of the best ways. It is nothing but the usage of the iterator() provided with the aid of the iterable interface to create an Iterator object. We are able to then use this Iterator object to iterate over the factors of the LinkedList.

while()

The code example here creates a LinkedList and adds five characters to it. It then uses an Iterator to iterate over the LinkedList and prints each character.

Algorithm

  • Step 1 − Import the necessary classes Iterator and LinkedList from the java.util package.

  • Step 2 − Define a public class named Tutorialspoint.

  • Step 3 − Define the main method.

  • Step 4 − Create a LinkedList object called list to store Characters.

  • Step 5 − Addition of the characters 'V', 'W', 'X', 'Y', and 'Z' to the LinkedList with the help of the add method.

  • Step 6 − Print the initial message "Using Iterator for iteration."

  • Step 7 − Create an Iterator object itr using the iterator method of the list.

  • Step 8 − Enter a while loop that continues as long as there are more elements in the LinkedList (itr.hasNext()).

  • Step 9 − Within each iteration, retrieve the next element from the Iterator (itr.next()) and store it in the obj variable of type Character.

  • Step 10 − Print the value of obj.

Example

package iterateLinkedList;

import java.util.Iterator;
import java.util.LinkedList;

public class Tutorialspoint {
   public static void main(String[] args) {
      LinkedList<Character> list = new LinkedList<>();
      list.add('V');
      list.add('W');
      list.add('X');
      list.add('Y');
      list.add('Z');

      System.out.println("Using Iterator for iteration");
      Iterator<Character> itr = list.iterator();
      while (itr.hasNext()) {
         Character obj = itr.next();
         System.out.println(obj);
      }
   }
}

Output

Using Iterator for iteration
V
W
X
Y
Z

Method 5: Using forEach()

Java 8 marked the debut of the forEach() method. Up until all items have been processed or the procedure meets an error, each Iterable element is subject to the task execution.

forEach()

The code creates a LinkedList and adds it with five integers. The elements of the LinkedList are then iterated over using the forEach method, and they are displayed.

Algorithm

  • Step 1 − Import the necessary class LinkedList from the java.util package.

  • Step 2 − Define a public class named TLP.

  • Step 3 − Define the main method.

  • Step 4 − Create a LinkedList object called linkedList to store Integers.

  • Step 5 − Addition of the integers 100, 200, 300, 400, and 500 to the LinkedList with the help of the add method.

  • Step 6 − Call the method iterateUsingForEach and pass the linkedList as an argument.

  • Step 7 − Define the method iterateUsingForEach that takes a LinkedList of Integers as a parameter.

  • Step 8 − Print the initial message "Iteration of the LinkedList by employing for each function: "

  • Step 9 − Use the forEach function of the LinkedList, passing a lambda expression that prints each element followed by a space.

  • Step 10 − Terminate the program

Example

import java.util.LinkedList;

public class TLP {
   public static void main(String[] args){

      LinkedList<Integer> linkedList = new LinkedList<>();

      linkedList.add(100);
      linkedList.add(200);
      linkedList.add(300);
      linkedList.add(400);
      linkedList.add(500);

      iterateUsingForEach(linkedList);
   }

   public static void iterateUsingForEach(LinkedList<Integer> linkedList){
      System.out.print("Iteration of the LinkedList by employing for each function : ");
      linkedList.forEach((element) -> System.out.print(element + " "));
   }
}

Output

Iteration of the LinkedList by employing for each function : 100 200 300 400 500

Conclusion

LinkedHashMap, a specialized subclass of HashMap, encompasses a doubly linked list that interconnects all its entries. Unlike its counterpart, HashMap, LinkedHashMap preserves the order in which elements are inserted. This characteristic makes LinkedHashMap the ideal choice for applications requiring traversing the map's entries in their original insertion sequence.

Updated on: 19-Oct-2023

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements