In
Groovy we can use the sort
and unique
methods to sort a collection or
remove duplicates from a collection. These methods alter the collection
on which they are invoked. This is a side effect we might want to
avoid. Therefore the sort
and unique
methods where changed and
we could pass a boolean
argument to indicate if the
original collection should be changed or that we must have a new
collection as the result of the methods, leaving the original
collection untouched. Since Groovy 2.4 we have two new methods which by
default return a new collection: toSorted
andtoUnique
.
In the following sample we see the new methods in action:
00.
@groovy.transform.Sortable
01.
@groovy.transform.ToString
02.
class
User
{
03.
String
username, email
04.
}
05.
06.
def
mrhaki1
=
new
User(username:
'mrhaki'
,
email:
'mrhaki@localhost'
)
07.
def
mrhaki2
=
new
User(username:
'mrhaki'
,
email:
'user@localhost'
)
08.
def
hubert1
=
new
User(username:
'hubert'
,
email:
'user@localhost'
)
09.
def
hubert2
=
new
User(username:
'hubert'
,
email:
'hubert@localhost'
)
10.
11.
12.
//
We make the list immutable,
13.
//
so we check the toSorted and toUnique methods
14.
//
do not alter it.
15.
def
users
= [mrhaki1, mrhaki2, hubert1, hubert2].
asImmutable
()
16.
17.
18.
//
toSorted
19.
def
sortedUsers
= users.toSorted()
20.
21.
//
@Sortable adds a compareTo method
22.
//
to User class to sort first by username
23.
//
and then email.
24.
assert
sortedUsers
== [hubert2, hubert1, mrhaki1, mrhaki2]
25.
26.
//
Original list is unchanged.
27.
assert
users
== [mrhaki1, mrhaki2, hubert1, hubert2]
28.
29.
//
Use toSorted with closure.
30.
def
sortedByEmail
= users.toSorted { a, b -> a.email <=> b.email }
31.
assert
sortedByEmail
== [hubert2, mrhaki1, mrhaki2, hubert1]
32.
33.
//
Or use toSorted with Comparator.
34.
//
@Sortable added static comparatorByProperty
35.
//
methods.
36.
def
sortedByEmailComparator
= users.toSorted(User.comparatorByEmail())
37.
assert
sortedByEmailComparator
== [hubert2, mrhaki1, mrhaki2, hubert1]
38.
39.
40.
//
toUnique with Comparator.
41.
def
uniqueUsers
= users.toUnique(User.comparatorByUsername())
42.
assert
uniqueUsers
== [mrhaki1, hubert1]
43.
assert
users
== [mrhaki1, mrhaki2, hubert1, hubert2]
44.
45.
//
toUnique with Closure.
46.
def
uniqueByEmail
= users.toUnique { a, b -> a.email <=> b.email }
47.
assert
uniqueByEmail
== [mrhaki1, mrhaki2, hubert2]