Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last KEY from a map in groovy?

I am trying to get the last KEY from this map in groovy. However, it seems like groovy doesn't have a method for returning the last key in the map.

def person = [fname: "john", sname: "smith", age: 25]

I have tried person.lastKey() and person.lastEntry() but these methods seems to be specific for java only.

like image 537
Saber Avatar asked Jan 30 '26 06:01

Saber


2 Answers

You can use person.keySet()[-1]​ or person.keySet().last()​

And to get whole entry use entrySet() instead of keySet()

See the Groovy demo online

like image 97
SURU Avatar answered Feb 02 '26 02:02

SURU


lastKey is part of the SortedMap interface and the Groovy map literal gives you an LinkedHashMap, which is the explanation, why your attempts failed.

Maps (the interface SortedMap inherits from) are on their own not ordered or sorted. So what you are asking here, will only work for ordered (which the Groovy map literal will give you) or sorted maps, so make sure you have one of those or you will see random elements instead of what you perceive as last. If order is important consider using a list of key-value-tuples instead.

like image 30
cfrick Avatar answered Feb 02 '26 01:02

cfrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!