Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the all but the last item of this given list in Groovy?

Tags:

groovy

It might sound simple, but am kind of struglling with the logic of how to print all but ignor the last element in the list. Any suggestion would be helpful.

code

    def list = [
        'homePage',
        'productPage',
        'basketPage',
        'categoryPage'
    ]
    def counter = 1
    list.each { element ->
        if (element == list.last()){
            list.remove(3)
            println "Item $counter -" + element 
        }
    }

Expected output

Item 1 - homePage
Item 2 - productPage
Item 3 - basketPage

like image 213
Learner Avatar asked Sep 19 '25 09:09

Learner


2 Answers

It can be shorter than @SteveD answer:

println list[0..-2]
like image 58
Will Avatar answered Sep 22 '25 00:09

Will


Groovy supports range operations on collections:

print list[0..list.size-2]

This will print:

[homePage, productPage, basketPage]
like image 31
SteveD Avatar answered Sep 21 '25 23:09

SteveD