15 May 2014

To make life easier, I have some eclipse save actions enabled. One of them is Convert for loops to enhanced. So every time I save a java file, all iterator based foor loops are converted to for-each loops.

As I aim for warning free code, I was surprised that a new warning appeared in a different part of the class I edited. I headed over to the warning and found the following code:

for(Object object : aCollection) {
	foo();
}

The warning said The value of the local variable object is not used. Appearently this is true. But why wasn't there a warning in the first place?

I compared the current version with latest from the local history and found the original code to be like:

for(Iterator<Object> iter = aCollection.iterator(); iter.hasNext();) {
	foo();
}

So the conversion was correct. But why is the current element of the iteration not used?
It turned out that foo needs to called as many times as there're elements in the collection.

So isn't there an elegant way to do this in java?
Short answer: no, there isn't.

Long answer:
In modern languages you have methods like timesRepeat: aBlock (Smalltalk) or times(Groovy) on number object.

As Java 8 introduced lambdas, I expected to have an equivalent method in the JDK, so that I can write

aCollection.size().times(() -> foo()); // does not compile due to missing times method

But no, there isn't. The only thing you can do, is to use the new forEach method:

aCollection.forEach(x -> foo());

But it's not as expressive and again the lambda parameter is unused. At least, it's shorter than the for loop.

Not even Apache Commons or Google Guava provide anything.
Am I missing something?