2016年12月6日 星期二

[ 常見問題 ] Sort list in descending order - groovy madness

Source From Here 
Question 
Consider I have a list as below: 
groovy:000> list = ['ab', 'a', 'abcd', 'abc']
===> [ab, a, abcd, abc]

How do I sort the list in descending order? 

How-To 
The Groovy list provide API sort for you to provide lambda on how to do sorting: 
groovy:000> list.sort{a,b-> a.size() <=> b.size()} // Sorting with length of string in ascending order
===> [a, ab, abc, abcd]
groovy:000> list // The sorting is in place
===> [a, ab, abc, abcd]
groovy:000> list.reverse() // To get a descending order
===> [abcd, abc, ab, a]
groovy:000> list // The reverse() will return new List which means it is not in place
===> [a, ab, abc, abcd] 

Supplement 
[ In Action ] The collective Groovy datatypes - Working with lists

沒有留言:

張貼留言

[ FP with Java ] Ch1 - What is functional programming

Preface   This chapter covers: ( Functional Programming in Java )  *  The benefits of functional programming *  Problems with side ef...