Set Operators with Groovy

Author: Paul King

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:

SetOperators

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.