Let's say I've got a list, like this...
def myList = ["first", 2, "third", 4.0];
How do I add (push) an element to the end of it? I come from a PHP background, and there I would just do something like $myList[] = "fifth";
. What's the equivalent of that in Groovy?
Groovy - add() Append the new value to the end of this List. This method has 2 different variants. boolean add(Object value) − Append the new value to the end of this List.
In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets.
Combine lists using the plus operator The plus operator will return a new list containing all the elements of the two lists while and the addAll method appends the elements of the second list to the end of the first one. Obviously, the output is the same as the one using addAll method.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6] assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6] //equivalent method for + def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6] assert [1, *[222, 333], 456] == [1, 222, 333, 456] assert [ *[1,2,3] ] == [1,2,3] assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9] def list= [1,2] list.add(3) //alternative method name list.addAll([5,4]) //alternative method name assert list == [1,2,3,5,4] list= [1,2] list.add(1,3) //add 3 just before index 1 assert list == [1,3,2] list.addAll(2,[5,4]) //add [5,4] just before index 2 assert list == [1,3,5,4,2] list = ['a', 'b', 'z', 'e', 'u', 'v', 'g'] list[8] = 'x' assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With