LinkedList Iterator | traversal of LinkedList - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Friday, December 2, 2016

LinkedList Iterator | traversal of LinkedList

In this post, We will see about some other methods of Java LinkedList and different way to traverse and iterate over Java LinkedList.

I strongly recommend to read about common methods of Java LinkedList.

Java LinkedList Iterator

Iterator is an interface in Java collection framework. The iterator returned by this class's iterator() method fail-fast. If the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove() method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Bellow is simple example of LinkedList iterator.

package com.walking.techie;

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

public class LinkedListIteratorDemo {

 public static void main(String[] args) {
  LinkedList<Integer> linkedList = new LinkedList<Integer>();
  linkedList.add(10);
  linkedList.add(25);
  linkedList.add(33);
  linkedList.add(47);
  linkedList.add(50);

  Iterator<Integer> iterator = linkedList.iterator();
  System.out.print("Element of linked list: ");
  while (iterator.hasNext()) {
   int temp = iterator.next();
   System.out.print(temp + " ");
  }

  // modification of linked list through remove method of iterator
  iterator = linkedList.iterator();
  while (iterator.hasNext()) {
   int temp = iterator.next();
   if (temp % 2 == 0)
    iterator.remove();
  }
  System.out.println("\nnumbers list after modifications: " + linkedList);

  // Now,changing it's structure while iterating

  iterator = linkedList.iterator();
  while (iterator.hasNext()) {
   int temp = iterator.next();
   System.out.print(temp + " ");
   if (temp == 33) {
    System.out.println();
    linkedList.add(11); // ConcurrentModificationException
   }
  }
 }
}

Output of above program is shown below:

Element of linked list: 10 25 33 47 50
numbers list after modifications: [25, 33, 47]
25 33
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
 at java.util.LinkedList$ListItr.next(LinkedList.java:888)
 at com.walking.techie.LinkedListIteratorDemo.main(LinkedListIteratorDemo.java:36)

Java LinkedList ListIterator

we can use ListIterator to traverse in both direction. The iterator returned by this class's listIterator(int) or listIterator() methods are fail-fast. If the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove() or add(Object) methods, the iterator will throw a ConcurrentModificationException.

package com.walking.techie;

import java.util.LinkedList;
import java.util.ListIterator;

public class LinkedListListIteratorDemo {

 public static void main(String[] args) {
  LinkedList<Integer> numbers = new LinkedList<Integer>();

  // add numbers from 1 to 10 in LinkedList
  for (int i = 1; i <= 10; i++) {
   numbers.add(i);
  }
  ListIterator<Integer> listIterator = numbers.listIterator();
  System.out.print("Element of numbers linked list: ");
  while (listIterator.hasNext()) {
   int temp = listIterator.next();
   System.out.print(temp + " ");
  }

  // modification of linked list through remove method of iterator
  listIterator = numbers.listIterator();
  while (listIterator.hasNext()) {
   int temp = listIterator.next();
   if (temp % 2 == 0) {
    listIterator.remove();
    listIterator.add(temp * 10);
   }
  }

  System.out.println("\nnumbers list after modifications: " + numbers);

  // traverse the linked list in backward direction
  listIterator = numbers.listIterator(numbers.size());
  System.out.print("Backward direction traversal of numbers list: ");
  while (listIterator.hasPrevious()) {
   int temp = listIterator.previous();
   System.out.print(temp + " ");
  }
  System.out.println();

  // below code will throw ConcurrentModificationException
  listIterator = numbers.listIterator();
  while (listIterator.hasNext()) {
   int temp = listIterator.next();
   System.out.print(temp + " ");
   if (temp == 9) {
    System.out.println();
    numbers.add(25);// ConcurrentModificationException
   }
  }
 }
}

Output of above program is shown below:

Element of numbers linked list: 1 2 3 4 5 6 7 8 9 10
numbers list after modifications: [1, 20, 3, 40, 5, 60, 7, 80, 9, 100]
Backward direction traversal of numbers list: 100 9 80 7 60 5 40 3 20 1
1 20 3 40 5 60 7 80 9
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
 at java.util.LinkedList$ListItr.next(LinkedList.java:888)
 at com.walking.techie.LinkedListListIteratorDemo.main(LinkedListListIteratorDemo.java:46)

Java LinkedList forEach

Java LinkedList forEach method was added in Java 8. It's useful when you want to perform same action on all the elements. The method argument Consumer is a functional interface. Below is an example of forEach method.

package com.walking.techie;

import java.util.LinkedList;
import java.util.function.Consumer;

public class LinkedListForEachDemo {

 public static void main(String[] args) {
  LinkedList<Integer> numbers = new LinkedList<Integer>();

  // add numbers from 1 to 10 in LinkedList
  for (int i = 1; i <= 10; i++) {
   numbers.add(i);
  }

  Consumer<Integer> consumer = new LinkedListForEachDemo().new MyConsumer<Integer>();
  numbers.forEach(consumer);
 }

 private class MyConsumer<T> implements Consumer<Integer> {

  @Override
  public void accept(Integer t) {
   System.out.println("consuming " + t);
  }
 }
}

Output of above program is shown below:

consuming 1
consuming 2
consuming 3
consuming 4
consuming 5
consuming 6
consuming 7
consuming 8
consuming 9
consuming 10

Java LinkedList descendingIterator

Java LinkedList descendingIterator method was added since Java 6. you can use this iterator to print element of LinkedList or Deque in reverse sequential order.

package com.walking.techie;

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

public class LinkedListReverseIterator {

 public static void main(String[] args) {
  LinkedList<String> language = new LinkedList<String>();
  language.add("C");
  language.add("CPP");
  language.add("JAVA");
  language.add("DOTNET");
  language.add("C#");
  language.add("PHP");
  System.out.println("Original language linked list " + language);
  Iterator<String> itr = language.descendingIterator();
  System.out.print("Reverse order of linked list [");
  while (itr.hasNext()) {
   String temp = itr.next();
   System.out.print(temp + " ");
  }
  System.out.println("]");
 }
}

Output of above program is shown below:

Original language linked list [C, CPP, JAVA, DOTNET, C#, PHP]
Reverse order of linked list [PHP C# DOTNET JAVA CPP C ]

1 comment :