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

Java – Convert Iterator to Stream

Use Spliterators.spliterator() or Spliterators.spliteratorUnknownSize() to convert an iterator to a stream

 

package com.pwn.stream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class IteratorToStream {

	public static void main(String[] args) {

		Iterator<String> iterator = Arrays.asList("A", "B", "C")
				.iterator();
		Spliterator<String> spliterator = Spliterators
				.spliteratorUnknownSize(iterator, 0);
		Stream<String> stream = StreamSupport.stream(spliterator,
				false);
		stream.forEach(System.out::println);

	}
}
A
B
C