12

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

代码:

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

肯定有不止一种方法可以做到这一点——所以我会把答案交给提供最优雅解决方案的人。

4

2 回答 2

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

获取降序

words = words.sort { -it.size() }
于 2009-04-08T09:14:56.487 回答
0

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

于 2020-06-24T16:21:19.587 回答