An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping.
A callback function is a simple function that defines the operation to be performed on a single element, and the forEach() method makes sure it will be performed on each element of an array. The forEach() method has a pretty straightforward syntax: forEach(callback(currentElement, index, arr), thisValue);
I had the same question and found using a ListIterator
worked. Similar to the test above:
List<String> list = Arrays.asList("zero", "one", "two");
ListIterator<String> iter = list.listIterator();
while (iter.hasNext()) {
System.out.println("index: " + iter.nextIndex() + " value: " + iter.next());
}
Make sure you call the nextIndex()
before you actually get the next()
.
Use your own variable and increment it in the loop.
Here's a way to do it using your own variable and keeping it concise:
List<String> list = Arrays.asList("zero", "one", "two");
int i = 0;
for (Iterator<String> it = list.iterator(); it.hasNext(); i++) {
String s = it.next();
System.out.println(i + ": " + s);
}
Output (you guessed it):
0: zero
1: one
2: two
The advantage is that you don't increment your index within the loop (although you need to be careful to only call Iterator#next once per loop - just do it at the top).
You can use ListIterator
to do the counting:
final List<String> list = Arrays.asList("zero", "one", "two", "three");
for (final ListIterator<String> it = list.listIterator(); it.hasNext();) {
final String s = it.next();
System.out.println(it.previousIndex() + ": " + s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With