This post originated from an RSS feed registered with Java Buzz
by dion.
Original Post: Iteration.each(): A closure view of iteration
Feed Title: techno.blog(Dion)
Feed URL: http://feeds.feedburner.com/dion
Feed Description: blogging about life the universe and everything tech
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
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