Java – Iterator, Iterable

Iterator

An Iterator is an interface which allows iterating over collection
It provides hasNext() and next() methods to iterate as shown below –

Iterator lists= Arrays.asList("A","B","C").iterator();
		while(lists.hasNext()) {
			System.out.println(lists.next());
		}

Iterable

An Iterable represents a collection which can be traversed.
Implementing the Iterable() interface allows an object to make use of a for-each loop.

package com.pwn.collection;
import java.util.Iterator;

public class CustomIterable {

	public static void main(String[] args) {
		System.out.println("Alphabet List below ");
		for (char c : new Alphabet()) {
			System.out.println(c);
		}
	}
}

class Alphabet implements Iterable<Character> {
	@Override
	public Iterator<Character> iterator() {
		return new Iterator<Character>() {
			char letter = 'a';

			@Override
			public boolean hasNext() {
				return letter <= 'z';
			}

			@Override
			public Character next() {
				return letter++;
			}

			@Override
			public void remove() {
				throw new 
                                UnsupportedOperationException(
		            "Doesn't make sense to remove a letter");
			}
		};
	}
}
Alphabet List below 
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s