CodesJava

Easy learning with example program codes

how to read all elements in linkedlist by using iterator in java?


LinkedList:

The LinkedList class extends AbstractSequentialList and implements the List and Deque interface. It uses linked list data structure to store elements. It can contain duplicate elements. It is not synchronized.

Note: It not provides the random access facility.

We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to iterate collection objects.

hasNext(): It returns true if the iteration has more elements.
next(): It returns the next element in the iteration.

Example:

package com.codesjava;
 
import java.util.Iterator;
import java.util.LinkedList;
 
public class Test {
  public static void main(String args[]){
	LinkedList<String> linkedList = new LinkedList<String>();
	linkedList.add("Jai");
	linkedList.add("Mahesh");
	linkedList.add("Naren");
	linkedList.add("Vivek");
	linkedList.add("Vishal");
	linkedList.add("Hemant");
        Iterator<String> iterator = linkedList.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
  }
}

Output

Jai
Mahesh
Naren
Vivek
Vishal
Hemant


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap