Killing our planet: New Climate Change Warning Do you remember when email was reliable?
Jan 31

Iteration.each(): A closure view of iteration

Tech Add comments

Looping through items in Java can be annoying. The most annoying part is how the construct for looping through an array/collection/string are not consistent.

E.g

for (int i = 0; i < objectArray.length; i++) {

for (Iterator iterator = collection.iterator(); iterator.hasNext();) {

We shouldn’t have to think about this, and languages like Groovy let us get around it. Since, I like this, I decided to back-port the idea into Java code, so now I have the following available to me in Java:

Iteration.each(collection, new ObjectUser() {
public void use(Object o) {
// do something with the element from the collection
}
});

Iteration.each(objectArray, new ObjectUser() {
public void use(Object o) {
// do something with the element from the Object[]
}
});

Iteration.each(string, new ObjectUser() {
public void use(Object o) {
// do something with the Character from the String
}
});

And there is also reverseEach(..) for the various data structures.

Small things. NOTE: Commons-Collections does this

Comments are closed.