Tuesday, May 19, 2009

More Groovier collections

Ranges are a beautiful ways of mangaing feinite sequence with a defined start and end.


a=1..5
println a // prints [1,2,3,4,5]
println a.size() // prints 5
println a.from // prints 1
println a.to //prints 5

x='a'..'f'
println x // prints [a,b,c,d,e,f]


You can also use ranges in subscript way to get part of a list.

a=[1,2,3,4,5,6]
x = 2
println a[0..2] // printrs [1,2,3]


You can also loop over each element of a range simple as follows

a=[1,2,3,4,5,6]
a.each{
println it
}

this prints all elements on new line.

Ranges can work with any objects whose class implments the Commprable interface having next and previous methods.

Another interesting thing that happens with all collections in any programming langugae is looping over it.Groovy has various options to this in many elegant ways.

Classical for .
This is usual for loop found in C,C++,JAVA,etc.this makes you feel home

for(int i=0;i<5;i++)
println i // you know what it prints


Iterable for.
This for works with any class that implments iterable like ranges,lists,maps,etc.
For on ranges

for(i in 0..5)
println i


For on lists

for(i in [1,2,3,4,5])
println i


For on maps

m=[a:"ant",b:"bat",c:"cat"]
for(e in m)
println e.key + "=" + e.value


For on strings

for(i in "Groovy")
println i // prints ewach character on newline


Another flexible and intuitive nature added to collections in groovy is that all Empty collections are evaluated to false in all boolean checks.
Following all prints true .(trick question : try removing ! :)

println ![]
println !''
println ![:]


Feel free to share your Groovy tips and tricks in the comments section

Read more...

Sociofluid