Skip to content

Instantly share code, notes, and snippets.

@shibli049
Last active November 26, 2018 13:03
Show Gist options
  • Save shibli049/7a2188193df97e7edf3a42aa3c676bea to your computer and use it in GitHub Desktop.
Save shibli049/7a2188193df97e7edf3a42aa3c676bea to your computer and use it in GitHub Desktop.
Iterate list/array with index
public class ForEachWith {
public static <T> Iterable<Index<T>> index(final T[] array) {
return () -> new Iterator<Index<T>>() {
int index = 0;
public boolean hasNext() {
return index < array.length;
}
public Index<T> next() {
return new Index(array[index], index++);
}
};
}
public static <T> Iterable<Index<T>> index(final List<T> list) {
return () -> new Iterator<Index<T>>() {
int index = 0;
public boolean hasNext() {
return index < list.size();
}
public Index<T> next() {
return new Index(list.get(index), index++);
}
};
}
}
public class Index<T> {
T value;
int index;
public Index(T value, int index) {
this.value = value;
this.index = index;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment