Wednesday, January 26, 2011

A lightweight anonymous visitor for Java collections

I got myself into a situation where I really wished that Java collections accepted a visitor interface of some kind so I could define one on the fly and get my job done. Alas, I decided to implement the utility myself and here's the result.

public interface IVisitor<T> {
void visit(T item);
}

public class CollectionUtils {
public static<T> void applyVisitor(Collection<T> collection, IVisitor<T> visitor) {
for (T item : collection)
visitor.visit(item);
}
}
A typical usage example would be:
public static void main(String[] args) {
CollectionUtils.applyVisitor(Arrays.asList(1, 2, 3, 4, 5), new IVisitor<Integer>() {
public void visit(Integer x) {
System.out.println(x);
}
});
}