Groovy Goodness: Removing Duplicate Elements in a Collection
We can easily remove duplicate elements in a collection with the different unique()
methods. Without any parameters the default comparator for the objects is used to determine duplicate elements. But we can also use a closure to define the rules for duplicate elements. The closure can have one parameter and then we must return a value that is used for comparison, or the closure has two parameters and then we must return an Integer value where 0 means the items are not unique. Finally we can pass our own Comparator
implementation to the unique()
method where we define when an element is unique or not.
00.
class
User
implements
Comparable {
01.
String username, email
02.
boolean
active
03.
04.
int
compareTo(Object other) {
05.
username <=> other.username
06.
}
07.
}
08.
09.
def
mrhaki1 =
new
User(username:
'mrhaki'
, email:
'mrhaki@localhost'
, active: false)
10.
def
mrhaki2 =
new
User(username:
'mrhaki'
, email:
'user@localhost'
, active: true)
11.
def
hubert1 =
new
User(username:
'hubert'
, email:
'user@localhost'
, active: false)
12.
def
hubert2 =
new
User(username:
'hubert'
, email:
'hubert@localhost'
, active: true)
13.
14.
// Caution: unique() changes the original collection, so
15.
// for the sample we invoke unique each time on a fresh new
16.
// user list.
17.
def
uniqueUsers = [mrhaki1, mrhaki2, hubert1, hubert2].unique()
18.
assert
2
== uniqueUsers.
size
()
19.
assert
[mrhaki1, hubert1] == uniqueUsers
20.
21.
// Use closure with one parameter.
22.
def
uniqueEmail = [mrhaki1, mrhaki2, hubert1, hubert2].unique { user ->
23.
user.email
24.
}
25.
assert
3
== uniqueEmail.
size
()
26.
assert
[mrhaki1, mrhaki2, hubert2] == uniqueEmail
27.
28.
// Use closure with two parameters.
29.
def
uniqueActive = [mrhaki1, mrhaki2, hubert1, hubert2].unique { user1, user2 ->
30.
user1.active <=> user2.active
31.
}
32.
assert
2
== uniqueActive.
size
()
33.
assert
[mrhaki1, mrhaki2] == uniqueActive
34.
35.
// Use a comparator.
36.
def
emailComparator = [
37.
equals: { delegate.equals(it) },
38.
compare: { first, second ->
39.
first.email <=> second.email
40.
}
41.
]
as
Comparator
42.
def
unique = [mrhaki1, mrhaki2, hubert1, hubert2].unique(emailComparator)
43.
assert
3
== unique.
size
()
44.
assert
[mrhaki1, mrhaki2, hubert2] == unique