Monday, December 22, 2008

On Iterator composition in Java

In my last blog post I mentioned that I would like to see library support for manipulating iterators included in the JDK. I for one, and I know that more people than me, have a set of iterator manipulation classes that I bring along from project to project, usually by copy/paste. This post is an elaboration on what the things are that I think should be included in the JDK, all communicated through code (The actual implementation is not as interesting as the API, and thus left as an exercise for the reader):

package java.util;

import java.util.iter.*;

public final class Iterators {
public <E> Iterable<E> empty() { ... }
public <S,T> Iterable<T> convert(Iterable<S> iterable, Converter<S,T> converter) { ... }
public <T> Iterable<T> upCast(Iterable<? extends T> iterable) { ... }
public <T> Iterable<T> downCast(Class<T> target, Iterable<?> iterable) { ... }
public <T> Iterable<T> append(Iterable<T>... iterables) { ... }
}

// These classes should preferably be reused from somewhere.
package java.util.iter;

public interface Converter<S,T> {
T convert(S source);
}

public interface Filter<E> {
boolean accept(E element);
}

And some sample uses:

package org.thobe.example;

import java.util.Iterators;
import java.util.iter.*;

class UsesIteratorComposition {
private class Something {}
private class Source extends Something {}
private class Target { Target(Source s) {} }

Iterable<Source> source = Iterators.empty();

void conversions() {
Iterable<Target> target = Iterators.convert(source, new Converter<Source,Target>() {
Target convert(Source source) {
return new Target(source);
}
});
}

void casts() {
Iterable<Something> something = Iterators.upCast(source);
Iterable<Source> back = Iterators.downCast(Source.class, something);
}

void append() {
Iterable<Source> source = Iterators.append(source, new ArrayList<Source>(){
{
add(new Source());
add(new Source());
}
});
}
}

No comments: