Thursday 17 January 2019

Groovy: Lists


List is an ordered collection of elements.

How to specify a list?
List can be created using [].

HelloWorld.groovy
primes = [2, 3, 5, 7]

println "size : ${primes.size()}"

for(i in primes){
 print i + " "
}

Output
size : 4
2 3 5 7

By default, Groovy create the instance of ArrayList, you can confirm the same using below program.


HelloWorld.groovy
primes = [2, 3, 5, 7]
println "\nclass : ${primes.class.name}"

Output
class : java.util.ArrayList

Create a list from range of elements
Using toList() method, you can create a list from range of elements.


HelloWorld.groovy
ints = (1..10).toList()

for(i in ints){
 println i
}

Output
1
2
3
4
5
6
7
8
9
10

You can add the elements to the list using index notation.


HelloWorld.groovy
primes = [2, 3, 5, 7]

primes[5] = 13

for(i in primes){
 println i
}

Output
2
3
5
7
null
13


As you observe the output, primes[5] is set with the value 13 and primes[4] is set with the value null.



Previous                                                 Next                                                 Home

No comments:

Post a Comment