Set Operators with Groovy
Published: 2023-11-14 03:22PM
Donald Raab posted an article about set operators using Java collections and Eclipse Collections. That post focuses on the union, intersection and difference operators. Weโll add in symmetric difference since Groovy supports operator overloading for that operator also.
First, a quick refresh about the operators for two sets A and B:
Weโll use the same emoji sets from Donaldโs post:
Set OCT = ["๐", "๐", "๐", "๐ฅง", "๐ซ", "๐", "๐ป", "๐ฝ", "๐", "๐ชต", "โ๏ธ"]
Set NOV = ["๐", "๐", "๐ฅง", "๐ฆ", "๐ฝ", "๐", "๐ชต", "โ๏ธ"]
Set DEC = ["๐ฅง", "๐ฆ", "โ๏ธ", "๐", "๐ฐ", "๐ท", "๐ชต", "๐", "โ๏ธ"]
Groovy lets you write the same code as in Donaldโs post but also offers operator overloading for these operators as follows:
assert (OCT & NOV & DEC) == ["๐ชต", "๐ฅง", "๐", "โ๏ธ"] as Set
assert (OCT | NOV | DEC) == ["๐ชต", "๐ฆ", "๐ฐ", "๐ท", "๐", "๐",
"๐ซ", "๐", "โ๏ธ", "๐ฅง", "โ๏ธ", "๐",
"๐", "๐", "๐ป", "๐ฝ", "๐"] as Set
assert (OCT - NOV - DEC) == ["๐ซ", "๐", "๐", "๐ป", "๐"] as Set
assert (NOV - OCT - DEC) == ["๐"] as Set
assert (DEC - OCT - NOV) == ["๐", "๐ฐ", "โ๏ธ", "๐ท"] as Set
assert (OCT ^ NOV ^ DEC) == ['โ๏ธ', '๐ฐ', '๐ท', '๐', '๐', '๐', '๐ซ', '๐',
'๐ป', '๐', '๐ฅง', '๐', '๐ชต', 'โ๏ธ'] as Set
assert (NOV ^ OCT ^ DEC) == ['๐', '๐', '๐', '๐ซ', '๐', '๐ป', '๐ฅง', 'โ๏ธ',
'๐', '๐ฐ', '๐ท', '๐ชต', '๐', 'โ๏ธ'] as Set
This code is using standard mutable Java collections,
but we could use the normal Set.of(โฆโ)
form and work with immutable sets
if that was our preference.
Also, since the Eclipse Collections Set implementations implement
the standard Java Set
interface, these operator overloading shorthands
also work when using Eclipse Collections. We simply use
Sets.immutable.of(โฆโ)
in our set definitions.
Whatโs more, since Groovy operator overloading is extensible, you can have similar shorthand notation for your own domain objects also. Enjoy!
This example used an alpha version of Groovy 5. Groovy 5 adds a little bit
of extra syntactic sugar when using sets. Earlier versions of Groovy
have union
and intersect
methods for sets.