Introduction: In this issue of real Groovy, Scott Davis presents a very good set of traversal methods that traverse arrays, lists, files, URLs, and many other things. Most impressively, Groovy provides a consistent mechanism to traverse all of these collections and other content.
Iterations are the foundation of programming. You will often encounter content that needs to be traversed, such as List, File, and JDBC ResultSet. The Java language almost always provides some way to help you iterate through what you need, but it's frustrating that it doesn't give a standard approach. Groovy's iterative approach is very practical, and at this point groovy programming is very different from Java programming. With some code examples (available from the download section), this article introduces the Almighty each () method of Groovy, leaving the Java language's iterative quirks behind.
Java Iteration Strategy
Suppose you have a java.util.List of a Java programming language. Listing 1 shows how to use programming to implement iterations in the Java language:
Listing 1. Java List iterations
Import java.util.*;
public class listtest{public
static void Main (string[] args) {
list<string> List = new Arraylist<strin G> ();
List.add ("Java");
List.add ("Groovy");
List.add ("JavaScript");
for (Iterator<string> i = List.iterator (); I.hasnext ();) {
String language = I.next ();
System.out.println ("I know" + language);
}
}
By providing a java.lang.Iterable interface where most collection classes can be shared, you can traverse Java.util.Set or java.util.Queue using the same method.