Java Collections Traversing | Set 2 - Walking Techie

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

Tuesday, August 9, 2016

Java Collections Traversing | Set 2

We strongly recommend to refer below Set 1 before moving on to this post.

Java Collections Traversing | Set 1

3.Using Enumeration

Enumeration is an interface and found in java.util package, whose object is always used for retrieving the data from any legacy collection framework variable (like vector, stack, HasTable etc.) only in forward direction but not in backward direction.

The Enumeration<E> interface has following method:

  • boolean hasMoreElements(): Returns true if enumeration object contains at least one more element otherwise, returns false.
  • E nextElement(): Returns next element of the enumeration if enumeration object contains at least one more element.

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework.

Example 4

Following is the example showing usage of Enumeration.

import java.util.Enumeration;
import java.util.Vector;

public class EnumerationDemo {

 public static void main(String[] args) {
  Vector<Integer> vector=new Vector<Integer>();
  vector.add(10);
  vector.add(20);
  vector.add(30);
  vector.add(40);
  vector.add(50);

  Enumeration<Integer> enumeration=vector.elements();
  System.out.println("Forward Direction..........");
  while(enumeration.hasMoreElements()){
   System.out.println(enumeration.nextElement());
  }
 }
}

Output of above program is shown below:

Forward Direction..........
10
20
30
40
50

Difference between Iterator and Enumeration interface.

Iterator Enumeration
Iterator can traverse legacy and non-legacy collection framework. Enumeration can traverse only legacy collection framework.
Iterator is fail-fast. Enumeration is not fail-fast.
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Enumeration does not support removing the elements.
In Iterator interface, method names are short. In Enumeration interface, method names are long.

4.Using for-each loop

We can use for-each loop to iterate over elements of the collection.

We can use the for-each loop to iterate over any collection whose implementation class implements the Iterable interface.

Syntax of for-each loop:

for(T  element : collectionName)  {
}

for each loop gets the iterator and call the hasNext() and next() methods.

Example 5

import java.util.ArrayList;
import java.util.List;

public class ForEachDemo {

 public static void main(String[] args) {
  List<String> nameList = new ArrayList<String>();
  nameList.add("Michel");
  nameList.add("Messi");
  nameList.add("Ronaldo");
  nameList.add("Xavi");

  for (String name : nameList) {
   System.out.println(name);
  }
 }
}

Output of above program is shown below:

Michel
Messi
Ronaldo
Xavi
Limitation of for-each loop

For-each has following limitations:

  • The for-each loop provides no way to visit previously visited elements.
  • We can't use for-each loop to remove elements from collection.
    The following code will throw a ConcurrentModificationException exception:
    public class ForEachDemo {
    
     public static void main(String[] args) {
      List<String> nameList = new ArrayList<String>();
      nameList.add("Michel");
      nameList.add("Messi");
      nameList.add("Ronaldo");
      nameList.add("Xavi");
    
      for (String name : nameList) {
       System.out.println(name);
       nameList.remove(name);// throws ConcurrentModificationException
      }
     }
    }
  • We have no way in for-each loop to start from middle of the collection.

5.Using forEach() method

Iterable interafce contain forEach(Consumer action) method. Iterable interface found in java.lang interface.

The method iterates over all elements and applies the action.

The forEach() method is available in all collection types that inherit from the Collection interface, because Collection interface implement Iterable interface.

Example 6

Following is the example showing usage of forEach.

import java.util.ArrayList;
import java.util.List;

public class ForEachDemo {

 public static void main(String[] args) {
  List<String> nameList = new ArrayList<String>();
  nameList.add("Michel");
  nameList.add("Messi");
  nameList.add("Ronaldo");
  nameList.add("Xavi");

  nameList.forEach(n->{
   System.out.println(n);
  });
 }
}

Output of above program is shown below:

Michel
Messi
Ronaldo
Xavi

No comments :

Post a Comment