Reputation: 461
How can I use Groovy to add an item to the beginning of a list?
Upvotes: 46
Views: 43767
Reputation: 15692
Caution!
From Groovy 2.5:
list.push( myObject )
Prior to Groovy 2.5 list.push
appends ... but from 2.5/2.6 (not yet Beta) it will (it seems) prepend, "to align with Java"... indeed, java.util.Stack.push
has always prepended.
In fact this push
method does not belong to List
, but to GDK 2.5 DefaultGroovyMethods, signature <T> public static boolean push(List<T> self, T value)
. However, because of Groovy syntax magic we shall write as above: list.push( myObject )
.
Upvotes: 9
Reputation: 26142
list.add(0, myObject);
You can also read this for some other valuable examples: http://groovy.codehaus.org/JN1015-Collections
Upvotes: 54
Reputation: 614
def list = [4, 3, 2, 1, 0]
list.plus(0, 5)
assert list == [5, 4, 3, 2, 1, 0]
You can find more examples at this link
Upvotes: 5
Reputation: 62254
Another option would be using the spread operator *
which expands a list into its elements:
def list = [2, 3]
def element = 1
assert [element, *list] == [1, 2, 3]
Another alternative would be to put the element into a list and concatenate the two lists:
assert [element] + list == [1, 2, 3]
Upvotes: 26