//Lists
//new empty list
def empty = []
assert empty.size() == 0
assert empty instanceof List
//creating a populated list with different objects
def myList = ["Test", 1, 1..5, null]
assert myList.size() == 4
//negative indexes for accessing the final elements
myList = [1,2,3,4,5]
assert myList[-1] == 5
assert myList[-1..-2] == [5,4]
assert myList[0..2] == [1,2,3]
//adding sth to it
myList << "AnotherElement"
assert myList.size() == 6
//but you can also use the java style
myList.add("something")
assert myList.size() == 7
//pop an element
assert myList.pop() == "something"
assert myList.pop() == "AnotherElement"
assert myList.size() == 5
//cutting and replacing a part of a list
def list = [0,1,2,3,4]
list[0..2] = [6,5] // different sizes !!
assert list == [6,5,3,4]
//creating a new list and reversing it
def someList = [1,2,3,4,5]
assert someList.reverse().join(',') == '5,4,3,2,1'
//sorting lists
myList = [10,5,15,25,20]
assert myList.sort { it } == [5,10,15,20,25]
//summing up
myList = [10, 20]
assert myList.sum() == 30
//convenience: instead of doing reverse().each{ } you can use reverseEach{}
def newList = []
[1,2,3].reverseEach{ newList << it }
assert newList.join(',') == '3,2,1'
//you can subtract Lists
assert ( [1,2,3] - [3,2] ).size() == 1
//you can add lists
assert ([1,2,3] + [4,5]).size() == 5
//why is plus() not part of the GDK description??? <a href="http://groovy.codehaus.org/groovy-jdk.html#cls44" >http://groovy.codehaus.org/groovy-jdk.html#cls44</a>
//you can multiply lists
assert ([1,2,3] * 2).join(',') == '1,2,3,1,2,3'
// you cannot divide lists <img src='http://www.snippetsmania.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />
//[1,2,3] / [1,2,3] //won't work
//of course you can have lists within lists
def listOne = ['a','b','c']
def listTwo = [1,2,3]
listOne << listTwo
assert listOne.size() == 4
//flatten will remove the inner lists
assert listOne.flatten().join(',') == 'a,b,c,1,2,3'
//Windows only
//as a special bonus, you can execute the elements of a list. First element is the command, others are parameters
//you can do the same with strings by the way ( "cmd /c dir".execute().text )
//def process = ['cmd', '/c', 'dir'].execute()
//println process.text //does print the execution of the dir command
Tag Archive for collections
snippets |
November 26, 2011