Using closures and collections in Groovy 1.0

Source: Internet
Author: User
Tags assert closure

1. Closure Package

Closures are a handy feature provided by many dynamic languages, something like an inner class in Java, except that there is only one method in the closure, but this method can have any number of arguments.

Java code

This code will output "Hello World".

1. def closure = { param -> println("hello ${param}") }
2. closure.call("world!")

The closure package "{}" is enclosed, "->" is preceded by a parameter, followed by a processing statement, can be invoked using call, or it can be executed directly after "{}" by using "()".

Closures can have more than one parameter, and each parameter is separated by ",". If there is only one argument can be omitted without writing, you can use the keyword "it" to represent.

We can write the above example as follows:

Java code

closure = { println("hello ${it}") }('world')

Or

Java code

1. closure = { param1,param2-> 
2.     println(param1+param2) }('hello ','world')

Several of the above are written out "Hello World".

2. Collection

(1) List

Java code

1. def list = [1, 2, 'hello', new java.util.Date()]
2. assert list.size() == 4 
3. assert list[1]==2 
4. assert list.get(2) == 'hello'

(2) Map

Java code

1. def map = ['name':'James', 'location':'London']
2. assert map.size() == 2 
3. assert map.get('name') == 'James'
4. assert map['location']=='London'

(3) Circulation

Java code

1. def list = [1, 2, 3]
2. for (i in list) {
3.   print i
4. }
5. println()
6.
7. list.each{item-> 
8.   print item 
9. }
10. println()
11.
12. ['name':'yanhua','addr':'beijing'].each{println it}
13. ['name':'yanhua','addr':'beijing'].each{key,value->println "${key} ^_^ ${value}"}

The results of the above operation are as follows:

123

123

Name=yanhua

Addr=beijing

Name ^_^ Yanhua

Addr ^_^ Beijing

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.