retainAll method
override
Removes all elements of this set that are not elements in elements
.
Checks for each element of elements
whether there is an element in this
set that is equal to it (according to this.contains
), and if so, the
equal element in this set is retained, and elements that are not equal
to any element in elements
are removed.
final characters = <String>{'A', 'B', 'C'};
characters.retainAll({'A', 'B', 'X'});
print(characters); // {A, B}
Implementation
@override
void retainAll(Iterable<Object?> elements) {
var valuesToRetain = Set<V>.identity();
for (var element in elements) {
if (element is! V) continue;
var key = _keyForValue(element);
if (!_baseMap.containsKey(key)) continue;
valuesToRetain.add(_baseMap[key] ?? null as V);
}
var keysToRemove = <K>[];
_baseMap.forEach((k, v) {
if (!valuesToRetain.contains(v)) keysToRemove.add(k);
});
keysToRemove.forEach(_baseMap.remove);
}