Skip to content

Instantly share code, notes, and snippets.

@ericwoodruff
Last active January 1, 2016 01:49
Show Gist options
  • Save ericwoodruff/8075511 to your computer and use it in GitHub Desktop.
Save ericwoodruff/8075511 to your computer and use it in GitHub Desktop.
Java for(each) Iterable, Each.withIndex
import java.util.Iterator;
public class Each {
public static class Indexed<T> {
public T value;
public int index;
public Indexed (T value, int index) {
this.value = value;
this.index = index;
}
}
public static <T> Iterable<Indexed<T>> withIndex (Iterable<T> iterable) {
return withIndex (iterable.iterator ());
}
public static <T> Iterable<Indexed<T>> withIndex (final Iterator<T> i) {
return new Iterable<Indexed<T>> () {
@Override
public Iterator<Indexed<T>> iterator () {
return new Iterator<Indexed<T>> () {
@Override
public boolean hasNext () {
return i.hasNext ();
}
@Override
public Indexed<T> next () {
return new Indexed<T> (i.next (), index++);
}
@Override
public void remove () {
i.remove ();
}
private int index = 0;
};
}
};
}
public static <T> Iterator<T> arrayIterator (final T[] array) {
return new Iterator<T> () {
@Override
public boolean hasNext () {
return index < array.length;
}
@Override
public T next () {
return array[index++];
}
@Override
public void remove () {
throw new UnsupportedOperationException ();
}
private int index = 0;
};
}
/*
No need for duplicate indexes
public static <T> Iterable<Indexed<T>> withIndex (T[] array) {
return withIndex (arrayIterator (array));
}
*/
public static <T> Iterable<Each.Indexed<T>> withIndex (final T[] array) {
return new Iterable<Each.Indexed<T>> () {
@Override
public Iterator<Each.Indexed<T>> iterator () {
return new Iterator<Each.Indexed<T>> () {
@Override
public boolean hasNext () {
return index < array.length;
}
@Override
public Each.Indexed<T> next () {
return new Indexed<T> (array[index], index++);
}
@Override
public void remove () {
throw new UnsupportedOperationException ();
}
private int index = 0;
};
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment