I have some Rust code which performs union and intersection operations on multiple sets. (BTreeSet
)
This is currently how I have written the code to chain those operations together. btree_map_X
is a BTreeMap
object.
let set_a = btree_map_1.keys().cloned().collect::<BTreeSet<i32>>();
let set_b = btree_map_2.keys().cloned().collect::<BTreeSet<i32>>();
let set_c = btree_map_3.keys().cloned().collect::<BTreeSet<i32>>();
let set_d = btree_map_4.keys().cloned().collect::<BTreeSet<i32>>();
let union_all =
set_a
.union(&set_b)
.cloned().collect::<BTreeSet<i32>>()
.union(&set_c)
.cloned().collect::<BTreeSet<i32>>()
.union(&set_d)
.cloned().collect::<BTreeSet<i32>>();
This doesn't seem particularly efficient, since after each union operation I am creating a whole new BTreeSet object using collect
.
Is there a more efficient way to do this, perhaps leveraging the power of lazy evaluation?