Groovy Goodness: Removing Duplicate Elements in a Collection - Messages from mrhaki
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 ownComparatorimplementation to theunique()method where we define when an element is unique or not.00.classUserimplementsComparable {01.String username, email02.booleanactive03.04.intcompareTo(Object other) {05.username <=> other.username06.}07.}08.09.defmrhaki1 =newUser(username:'mrhaki', email:'mrhaki@localhost', active: false)10.defmrhaki2 =newUser(username:'mrhaki', email:'user@localhost', active: true)11.defhubert1 =newUser(username:'hubert', email:'user@localhost', active: false)12.defhubert2 =newUser(username:'hubert', email:'hubert@localhost', active: true)13.14.// Caution: unique() changes the original collection, so15.// for the sample we invoke unique each time on a fresh new16.// user list.17.defuniqueUsers = [mrhaki1, mrhaki2, hubert1, hubert2].unique()18.assert2== uniqueUsers.size()19.assert[mrhaki1, hubert1] == uniqueUsers20.21.// Use closure with one parameter.22.defuniqueEmail = [mrhaki1, mrhaki2, hubert1, hubert2].unique { user ->23.user.email24.}25.assert3== uniqueEmail.size()26.assert[mrhaki1, mrhaki2, hubert2] == uniqueEmail27.28.// Use closure with two parameters.29.defuniqueActive = [mrhaki1, mrhaki2, hubert1, hubert2].unique { user1, user2 ->30.user1.active <=> user2.active31.}32.assert2== uniqueActive.size()33.assert[mrhaki1, mrhaki2] == uniqueActive34.35.// Use a comparator.36.defemailComparator = [37.equals: { delegate.equals(it) },38.compare: { first, second ->39.first.email <=> second.email40.}41.]asComparator42.defunique = [mrhaki1, mrhaki2, hubert1, hubert2].unique(emailComparator)43.assert3== unique.size()44.assert[mrhaki1, mrhaki2, hubert2] == unique
浙公网安备 33010602011771号