Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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[]) {
ListString> 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 Java’ section, 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 EvenListT> implements IterableT> {
private ListT> list;

EvenList(ListT> list) {
this.list = list;
}

public IteratorT> iterator() {
return new EvenIteratorT>();
}

@SuppressWarnings("hiding")
private class EvenIteratorT> implements IteratorT> {
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[]) {
ListInteger> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

EvenListInteger> 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
Implement custom iterator in Java
How to traverse TreeMap in Java
How to traverse HashMap in Java
Why Wait and Notify is in Object Class
Dead lock Example





This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Provide for-each behavior to custom collection

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×