Friday, July 22, 2011

Java Zipper

A colleague moving between Python and Java asked me if there were an implementation of zip. Handling arbitrary tuples is challenging in Java, but the simple 2-tuple is straight-forward enough:

public final class Pair<T, U> {
    public final T first;
    public final U second;

    public static <T, U> Pair<T, U> pair(final T first, final U second) {
        return new Pair<T, U>(first, second);
    }

    private Pair(final T first, final U second) {
        this.first = first;
        this.second = second;
    }
}

public final class Zipper {
    public static <T, U> Iterable<Pair<T, U>> zip(
            final T[] first, final Iterable<U> second) {
        return zip(asList(first), second);
    }

    public static <T, U> Iterable<Pair<T, U>> zip(
            final Iterable<T> first, final U[] second) {
        return zip(first, asList(second));
    }

    public static <T, U> Iterable<Pair<T, U>> zip(
            final T[] first, final U[] second) {
        return zip(asList(first), asList(second));
    }

    public static <T, U> Iterable<Pair<T, U>> zip(
            final Iterable<T> first, final Iterable<U> second) {
        return new Iterable<Pair<T, U>>() {
            @Override
            public Iterator<Pair<T, U>> iterator() {
                return new Iterator<Pair<T, U>>() {
                    private final Iterator<T> fit
                            = first.iterator();
                    private final Iterator<U> sit
                            = second.iterator();

                    @Override
                    public boolean hasNext() {
                        return fit.hasNext() && sit.hasNext();
                    }

                    @Override
                    public Pair<T, U> next() {
                        return pair(fit.next(), sit.next());
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

    private Zipper() {
    }
}

I found several functional Java libraries but none as simple as my colleague wanted.

Post a Comment