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
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – LinkedList Iterator example

By Chaitanya Singh | Filed Under: Java Collections

In the last post we learnt how to traverse a LinkedList using ListIterator. Here we will learn how to iterate a LinkedList using Iterator.

Example

The steps we followed in the below program are:

1) Create a LinkedList
2) Add element to it using add(Element E) method
3) Obtain the iterator by calling iterator() method
4) Traverse the list using hasNext() and next() method of Iterator class.

import java.util.LinkedList;
import java.util.Iterator;
public class IteratorExample {
 
 public static void main(String[] args) {
 
    // Create a LinkedList
    LinkedList<String> linkedlist = new LinkedList<String>();
 
    // Add elements to LinkedList
    linkedlist.add("Delhi");
    linkedlist.add("Agra");
    linkedlist.add("Mysore");
    linkedlist.add("Chennai");
    linkedlist.add("Pune");
 
    // Obtaining Iterator
    Iterator it = linkedlist.iterator();
 
    // Iterating the list in forward direction
    System.out.println("LinkedList elements:");
    while(it.hasNext()){
       System.out.println(it.next());
    }
 }
}

Output:

LinkedList elements:
Delhi
Agra
Mysore
Chennai
Pune

Enjoyed this post? Try these related posts

  1. Java ArrayList trimToSize() Method example
  2. Difference between List and Set in Java
  3. Java – Get first and last elements from LinkedList example
  4. How to convert an array to ArrayList in java
  5. LinkedList in Java with Example
  6. Java – Replace element in a LinkedList example

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 – 2021 BeginnersBook . Privacy Policy . Sitemap