tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collections > Iterable Simplified

Iterable Simplified 

The following code shows how to implement custom Iterable object. If the object implements Iterable interface it can be used as a target in for each loop. The below example shows both forward and backward iteration.

File Name  :  
com/bethecoder/tutorials/collections/IterableTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.collections;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class IterableTest {

   public static void main(String[] args) {
     
     String [] strings = "ONE""TWO""THREE""FOUR""FIVE""SIX" };
     IterableObject iterableObj = new IterableObject(strings);
     ReverseIterableObject reverseIterableObj = new ReverseIterableObject(strings);
     
     for (String str : iterableObj) {
       System.out.println(str);
     }
     
     System.out.println("----------------");
     
     for (String str : reverseIterableObj) {
       System.out.println(str);
     }

   }
}

class IterableObject implements Iterable<String> {

  private String [] myStrings = null;
  
  public IterableObject(String [] myStrings) {
    this.myStrings = myStrings;
  }
  
  public Iterator<String> iterator() {
    
    return new Iterator<String>() {

      private int count = 0;

      public boolean hasNext() {
        return count < myStrings.length;
      }

      public String next() {
        
        if (count < myStrings.length) {
          return myStrings[count++];
        }
        
        throw new NoSuchElementException();
      }

      public void remove() {        
        throw new UnsupportedOperationException();
      }
      
    };
  }  
}

class ReverseIterableObject implements Iterable<String> {

  private String [] myStrings = null;
  
  public ReverseIterableObject(String [] myStrings) {
    this.myStrings = myStrings;
  }
  
  public Iterator<String> iterator() {
    
    return new Iterator<String>() {

      private int count = myStrings.length-1;

      public boolean hasNext() {
        return count >= 0;
      }

      public String next() {
        
        if (count >= 0) {
          return myStrings[count--];
        }
        
        throw new NoSuchElementException();
      }

      public void remove() {        
        throw new UnsupportedOperationException();
      }
      
    };
  }
  
}
   

It gives the following output,
ONE
TWO
THREE
FOUR
FIVE
SIX
----------------
SIX
FIVE
FOUR
THREE
TWO
ONE



 
  


  
bl  br