Last active
January 1, 2016 01:49
-
-
Save ericwoodruff/8075511 to your computer and use it in GitHub Desktop.
Java for(each) Iterable, Each.withIndex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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