union method
Returns a new lazy Iterable that represents the union of this iterable and the other iterable.
The returned Iterable lazily yields unique elements from both iterables. It uses a HashSet to track existing elements and ensure each element is yielded only once, effectively removing duplicates.
-
Parameters:
other: The iterable to be combined with this iterable.
-
Returns: A new lazy Iterable containing the unique elements from both this iterable and the
otheriterable. -
Examples:
List<int> firstList = [1, 2, 3]; List<int> secondList = [2, 3, 4]; Iterable<int> unionSet = firstList.union(secondList); print(unionSet.toList()); // [1, 2, 3, 4]
Note: The function does not preserve the order of elements. Elements are yielded in the order they are encountered without duplicates.
Implementation
Iterable<T> union(Iterable<T> other) sync* {
var existing = HashSet<T>();
for (var element in this) {
if (existing.add(element)) yield element;
}
for (var element in other) {
if (existing.add(element)) yield element;
}
}