Friday, 29 July 2016

Provide for-each behavior to custom collection


‘foreach’ statement is used to traverse a collection. Following example explains how to traverse a collection using for-each loop.
import java.util.Arrays;
import java.util.List;

public class Test {
 public static void main(String args[]) {
  List<String> list = Arrays.asList("Hi", "ptr", "How", "are", "you");

  for (String s : list) {
   System.out.println(s);
  }
 }
}


Output
Hi
ptr
How
are
you


To support for-each loop to your custom collection, it should implement Iterable interface. In ‘Implement custom iterator in Javasection, I explained about Iterable interface. . Suppose my collection has elements like 1, 2, 3, 4, 5, 6, 7, 8, 9. My for-each should traverse the elements at even positions like 1(is at 0th position), 3(is at 2nd position), 5, 7, 9.
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class EvenList<T> implements Iterable<T> {
 private List<T> list;

 EvenList(List<T> list) {
  this.list = list;
 }

 public Iterator<T> iterator() {
  return new EvenIterator<T>();
 }

 @SuppressWarnings("hiding")
 private class EvenIterator<T> implements Iterator<T> {
  int size = list.size();
  int currentPointer = 0;

  public boolean hasNext() {
   return (currentPointer < size);
  }

  public T next() {
   if (!hasNext()) {
    throw new NoSuchElementException();
   }

   @SuppressWarnings("unchecked")
   T val = (T) list.get(currentPointer);
   currentPointer += 2;

   return val;
  }

 }

}


Total logic is in the next() method, here I am checking for an element in the collection using hasNext() method, it it returns false, I am throwing NoSuchElementException(). If element exists, then I am saving current element to a temporary variable and incrementing the currentPointer to 2.
import java.util.Arrays;
import java.util.List;

public class TestEvenList {
 public static void main(String args[]) {
  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

  EvenList<Integer> myList = new EvenList(list);

  for(int i: myList){
   System.out.println(i);
  }
 }
}


Run above application, you will get following output.

1
3
5
7
9


You may like



No comments:

Post a Comment