【问题标题】:Groovy: How do I sort an ArrayList of String:s in length-of-string order?Groovy:如何按字符串长度顺序对 String:s 的 ArrayList 进行排序?
【发布时间】:2010-10-18 06:09:56
【问题描述】:

如何在 Groovy 中按字符串长度顺序对 String 中的 ArrayList 进行排序?

代码:

def words = ['groovy', 'is', 'cool']
// your code goes here:
// code that sorts words in ascending length-of-word order
assert words == ['is', 'cool', 'groovy']

肯定有不止一种方法可以做到这一点 - 所以我会将答案授予提供最优雅解决方案的人。

【问题讨论】:

    标签: string sorting groovy arraylist


    【解决方案1】:
    words = words.sort { it.size() }
    

    按降序排列

    words = words.sort { -it.size() }
    

    【讨论】:

    • 很遗憾,即使在 2013 年,这也不是官方 groovy 文档的一部分(至少我从未找到过这个)。
    • @Panique:您希望找到什么?排序方法在 API 文档中,剩下的只是了解闭包的工作原理。
    • @MichaelBorgwardt 我刚刚在-it.size() 中搜索了几个小时、几天、几周、几年甚至几个世纪的小减号。以前从未见过。一个好的文档应该提供这样的信息,因为这是基本的东西。
    • 谢谢!升序有效,但是,- 的降序不
    【解决方案2】:

    如果在接受的解决方案中{ -it.size() } 不适用于降序,你可以试试这个: { -1 * it.size() }

    【讨论】:

    • 这些东西有什么不同?
    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2016-03-11
    • 2021-04-05
    相关资源
    最近更新 更多