How to drop the first element from a list, in place in groovy?
In JS/ruby, it is done with shift, shift! method.
How to drop the first element from a list, in place in groovy?
In JS/ruby, it is done with shift, shift! method.
Another option is by slicing:
def lst = [1,2,3,4,5]
println lst
lst = lst[1..-1]
println lst
Output:
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
You can use the tail method which is specifically there for getting "everything except the first item:
groovy:000> [1,2,3,4,5].tail()
===> [2, 3, 4, 5]
this in contrast to head (head and tail...makes sense) which will give you the first item (same as first()):
groovy:000> [1,2,3,4,5].head()
===> 1
groovy:000> [1,2,3,4,5].first()
===> 1
correction: if with "in place" we mean modifying the original list then I think removeAt and remove are your friends as suggested by a different answer.
remove / removeAt do not return you the resulting list (they return the removed element) which is unfortunate but seems like they are the only ones actually modifying the list in place.
Though it should be noted that even remove/removeAt at least for the ArrayList imlementation does do a System.arraycopy under the hood which means still copying the data. Granted the copy is done in probably the fastest way possible on the jvm, but still, a copy.
For the constant time removal you might have been looking for you can for example make sure your list is an instance of LinkedList:
def list = [1,2] as LinkedList
list.remove(0)
at which point the first element is "unlinked" in constant time without any copying of data.
how about using pop() method:
def list = ["a", false, 2]
assert list.pop() == 'a'
assert list == [false, 2]
Try removeAt(0) or remove(0):
From the docs for removeAt():
Modifies this list by removing the element at the specified position in this list. Returns the removed element. Essentially an alias for List#remove(int) but with no ambiguity for List<Integer>.
def lst = [1, 2, 3]
println lst
lst.removeAt(0) // or lst.remove(0)
println lst
Output:
[1, 2, 3]
[2, 3]
Also not inline (modifying the list itself), but drop is used to drop n
(like the subject requested), and ignores whether n is greater than the size of the collection (unlike e.g. tail()):
groovy:000> [1,2,3].drop(1)
===> [2, 3]
groovy:000> [1,2,3].drop(5)
===> []