Saturday, June 3, 2017

Java Iterable Vs Iterator

In my experience, the most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.

Iterator is single traversal.
In Java 5

  1. Iterable<SomeObj> objs = new Iterable>() {
  2. public Iterator<SomeObj> iterator() {
  3. return object.getChildren();
  4. }
  5. };

In Java 8, working with legacy Iterator-based interfaces is a little easier, thanks to method references. The Service.getPorts example above could be written as:
  1. Iterable<SomeObj> objs = object::getChildren;
And you can even inline it directly into the for loop:

  1. for (SomeObj objs : object::getChildren) {
  2. // ...
  3. }
A Collection is an Iterable... So you can write:

public static void main(String args[]) {
    List<String> list = new ArrayList<String>();
    list.add("a string");

    Iterable<String> iterable = list;
    for (String s : iterable) {

No comments: