How many ways to iterate a LinkedList in Java?

JavaObject Oriented ProgrammingProgramming

A LinkedList is a data structure that contains a group of nodes connected in a sequential manner with a pointer. A LinkedList can behave as a dynamic array and it allocates space for each element separately in its own block of memory called a Node. Each node contains two fields, a "data" field to store an element type the list holds and a "next" field which is a pointer used to link one node to the next node.

We can iterate the elements of a LinkedList in three ways in Java.

Using Iterator

We can iterate the elements of a LinkedList through the Iterator class.

Example

import java.util.*;
public class LinkedListIteratorTest {
   public static void main(String[] args) {
      List<String> list = new LinkedList<>();
      list.add("Kohli");
      list.add("Morgan");
      list.add("Williamson");
      list.add("Smith");
      list.add("Kohli");
      Iterator it = list.iterator();
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}

Output

Kohli
Morgan
Williamson
Smith
Kohli


Using ListIterator

We can iterate the elements of a LinkedList through ListIterator class.

Example

import java.util.*;
public class LinkedListWithListIteratorTest {
   public static void main(String[] args) {
      List<String> list = new LinkedList<>();
      list.add("Kohli");
      list.add("Morgan");
      list.add("Williamson");
      list.add("Smith");
      list.add("Kohli");
      ListIterator<String> li = list.listIterator();
      while(li.hasNext()) {
         System.out.println(li.next());
      }
   }
}

Output

Kohli
Morgan
Williamson
Smith
Kohli


sing For-each loop

We can also iterate the elements of a LinkedList through the for-each loop.

Example

import java.util.*;
public class LinkedListForEachTest {
   public static void main(String[] args) {
      List<String> list = new LinkedList<>();
      list.add("Kohli");
      list.add("Morgan");
      list.add("Williamson");
      list.add("Smith");
      list.add("Kohli");
      for(String str : list) {
         System.out.println(str);
      }
   }
}

Output

Kohli
Morgan
Williamson
Smith
Kohli
raja
Published on 06-Sep-2019 12:17:10
Advertisements