Skip to content

Instantly share code, notes, and snippets.

@herrphon
Last active September 1, 2016 22:48
Show Gist options
  • Save herrphon/a48dea5ccbb5fb92891ebb31052402bf to your computer and use it in GitHub Desktop.
Save herrphon/a48dea5ccbb5fb92891ebb31052402bf to your computer and use it in GitHub Desktop.
package de.aeffle.for_each_with_counter;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
public class ForEachLoopWithIndex {
@Test
public void blubb() {
List<String> strings = ImmutableList.of("one", "two", "three");
for (String string : strings) {
System.out.println("String: " + string);
}
System.out.println("---");
for (Index<String> each: With.index(strings)) {
System.out.println("Index: " + each.index);
System.out.println("Value: " + each.value);
System.out.println("---");
}
}
}
class Index<T> {
public final T value;
public final int index;
public Index(int index, T value) {
this.index = index;
this.value = value;
}
}
class With {
public static <T> Iterable<Index<T>> index(final List<T> list) {
return () -> new Iterator<Index<T>>() {
int index = 0;
Iterator<T> iterator = list.iterator();
public boolean hasNext() {
return iterator.hasNext();
}
public Index<T> next() {
return new Index( index++, iterator.next());
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment