beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to loop LinkedList in Java

By Chaitanya Singh | Filed Under: Java Collections

In the last tutorial we discussed LinkedList and it’s methods with example. Here we will see how to loop/iterate a LinkedList. There are four ways in which a LinkedList can be iterated –

  1. For loop
  2. Advanced For loop
  3. Iterator
  4. While Loop

Example:

In this example we have a LinkedList of String Type and we are looping through it using all the four mentioned methods.

package beginnersbook.com;
import java.util.*;

public class LinkedListExample {

   public static void main(String args[]) {
      /*LinkedList declaration*/
      LinkedList<String> linkedlist=new LinkedList<String>();
      linkedlist.add("Apple");
      linkedlist.add("Orange");
      linkedlist.add("Mango");

      /*for loop*/
      System.out.println("**For loop**");
      for(int num=0; num<linkedlist.size(); num++)
      {
    	  System.out.println(linkedlist.get(num));
      }

      /*Advanced for loop*/
      System.out.println("**Advanced For loop**");
      for(String str: linkedlist)
      {
    	  System.out.println(str);
      }

      /*Using Iterator*/
      System.out.println("**Iterator**");
      Iterator i = linkedlist.iterator();
      while (i.hasNext()) {
	  System.out.println(i.next());
      }

      /* Using While Loop*/
      System.out.println("**While Loop**");
      int num = 0;
      while (linkedlist.size() > num) {
	  System.out.println(linkedlist.get(num));
	  num++;
      }

   }
}

Output:

**For loop**
Apple
Orange
Mango
**Advanced For loop**
Apple
Orange
Mango
**Iterator**
Apple
Orange
Mango
**While Loop**
Apple
Orange
Mango

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap