Last active
November 26, 2018 13:03
-
-
Save shibli049/7a2188193df97e7edf3a42aa3c676bea to your computer and use it in GitHub Desktop.
Iterate list/array with index
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
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