Combat Groovy:for Each profiling-iterate using the most familiar method

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.