If we have a simple list like
1 |
[code]List list = [4, 2, 9, 6, 7, 8, 2][/code] |
We can easily sort this list using
1 |
[code]assert list.sort() == [2, 2, 4, 6, 7, 8, 9][/code] |
or by using closure like
1 |
[code]assert list.sort { it } == [2, 2, 4, 6, 7, 8, 9][/code] |
Both gives us a list sorted in ascending order.
sort modifies the original list i.e., original list is also sorted. If you do not want to modify the original list then just pass false as argument like
1 2 3 4 |
[code] list.sort(false) list.sort(false) { it } [/code] |
Using closure we can also sort object by its property:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[code] class User { String name Integer age @Override String toString() { return name } } List userList = [new User(name: 'Manish', age: 25), new User(name: 'Kumar', age: 26), new User(name: 'JFT', age: 24)] assert userList.sort { it.name } == ['JFT', 'Kumar', 'Manish'] assert userList.sort { it.age } == ['JFT', 'Manish', 'Kumar'] assert userList.sort { it.name.size() } == ['JFT', 'Kumar', 'Manish'] [/code] |
We can also sort list in descending order but if we compare numeric fields only
1 2 3 4 5 |
[code] assert list.sort { -it } == [9, 8, 7, 6, 4, 2, 2] assert userList.sort { -it.age } == ['Kumar', 'Manish', 'JFT'] assert userList.sort { -it.name.size() } == ['Manish', 'Kumar', 'JFT'] [/code] |
Hope this helps 🙂 .
Recent Comments