Groovy: How do I sort an ArrayList of String:s in length-of-string order?
20,704
words = words.sort { it.size() }
To get descending order
words = words.sort { -it.size() }
Author by
knorv
Updated on July 05, 2022Comments
-
knorv almost 2 years
How do I sort an
ArrayList
ofString
's in length-of-string order in Groovy?Code:
def words = ['groovy', 'is', 'cool'] // your code goes here: // code that sorts words in ascending length-of-word order assert words == ['is', 'cool', 'groovy']
There are certainly more than one way to do it - so I'll grant the answer to the person who provides the most elegant solution.
-
Sliq about 11 yearsit's a shame that this is - even in 2013 - not part of the official groovy docs (at least i have never found this).
-
Michael Borgwardt about 11 years@Panique: what exactly would you expect to find? The sort method is in the API docs, the rest is just understanding how closures work.
-
Sliq about 11 years@MichaelBorgwardt I just searched for hours, days, weeks, years and maybe centuries for that little minus in
-it.size()
. Never seen that before. A good documentation should give such information, as this is basic stuff. -
RST almost 11 yearsThanks ! ascending works, however, the descending order with
-
does not -
Chris almost 4 yearsHow are those things different?