I've gathered together a few more thoughts on improving the enhanced for-each loops.
The basic idea is to take this very popular Java 5 feature and provide the missing parts.
Control access
One of the more frustrating parts of the Java 5 for-each loop is when you are 80% through writing a loop, and you discover you need to remove an item, or require the loop index.
At that point, you have to go back and manually change the loop to one of the old formats (in Eclipse at least).
This is a hassle.
Perhaps more importantly is that the older for loops simply aren't as clear in their intentions, aren't very DRY, and are definitely more error-prone.
As a result, I've documented my proposal to improve the for-each loop with control access.
For example, to access the loop index:
Collection<String> coll = new ArrayList<String>();
for (String str : coll : it) {
System.out.println("Item: " + str + ", Index: " + it.index());
}
And here is an example of removing an item:
List<String> list = new ArrayList<String>();
for (String str : list : it) {
if (str == null || it.isFirst()) {
it.remove();
}
}
As can be seen, the syntax simply involves adding another colon and a 'variable' name.
The 'variable' can be used access loop control and manipulation functions.
Note that the additional colon and 'variable' are of course optional for full backwards compatibility.
The document discusses two strategies for implementing the syntax - either via real Java types or as a language level feature.
Please read the document for more information.
Maps
I have updated my previous document about extending for-each to maps.
The download of the javac implementation remains available from Kijaro.
Summary
It seems increasingly unlikely that there is time for closures to make it into Java 7.
There are also many developers expressing real doubts as to whether the complexity of control invocation is just too much for the venerable Java language.
The alternative is smaller improvements like these two.
They provide an easy to grasp extension to the popular Java 5 for-each loop, that might still be possible to deliver in Java 7.
Opinions welcome, as always.