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() }
Share:
20,704
knorv
Author by

knorv

Updated on July 05, 2022

Comments

  • knorv
    knorv almost 2 years

    How do I sort an ArrayList of String'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
    Sliq about 11 years
    it'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
    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
    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
    RST almost 11 years
    Thanks ! ascending works, however, the descending order with - does not
  • Chris
    Chris almost 4 years
    How are those things different?