Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to Add item to start of list using Groovy?

Writer Matthew Harrington

How can I use Groovy to add an item to the beginning of a list?

4 Answers

list.add(0, myObject);

You can also read this for some other valuable examples:

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]​
1

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 ).

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

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy