Sub topic 4
Sets: Unique Elements and Set Operations
This chapter assumes you can write basic Dart (variables, functions, control flow). It also assumes you know generic type notation such as List<int> and what a nullable type like int? means. You have already seen lists and maps, so this chapter focuses on what makes a set different and on the operations only sets offer.
What a set is
A Set<E> is a collection of elements with no duplicates. Adding an element that is already present does nothing. A set has no index, so mySet[0] is a compile error. You reach elements by checking membership or by iterating.
Sets are the right tool for three jobs:
- Removing duplicates.
- Asking "have I seen this before?" quickly.
- Combining groups of values with union, intersection, and difference.
The default set, created by a literal or by Set(), is a LinkedHashSet. Membership checks take constant time on average, and iteration follows insertion order. The default set also relies on == and hashCode to decide whether two elements are the same. The chapter on equality covers that in detail.
Creating sets
A set literal uses curly braces around comma-separated elements. An empty {} is ambiguous, because maps also use curly braces. With no other information, Dart treats {} as a map.
void main() {
final tags = <String>{'dart', 'flutter'}; // Set<String>
final empty = <int>{}; // an empty Set<int>
Set<int> alsoEmpty = {}; // the declared type makes this a set
final fromList = Set<int>.from([1, 2, 2, 3]); // {1, 2, 3}
final viaMethod = [4, 4, 5].toSet(); // {4, 5}
final copy = Set<String>.of(tags); // a new, independent set
print(tags);
print(empty.isEmpty);
print(alsoEmpty.runtimeType.toString().contains('Set')); // true
print(fromList);
print(viaMethod);
print(copy);
}If you write final x = {}; the variable is a Map<dynamic, dynamic>. When you want an empty set, either annotate the variable's type or put type arguments before the braces, as in <int>{}.
A literal with at least one element is inferred correctly. {1, 2} is a Set<int>, while {'a': 1} is a Map<String, int>.
Adding, checking, and removing
add returns a bool: true if the element was new, false if it was already present. remove also returns a bool, telling you whether anything was removed. You can use these return values instead of a separate contains call.
void main() {
final tags = <String>{'dart', 'flutter'};
print(tags.add('web')); // true
print(tags.add('dart')); // false, already present
print(tags.contains('web')); // true
print(tags.remove('web')); // true
print(tags.remove('web')); // false, nothing to remove
tags.addAll(['ui', 'dart', 'ui']);
print(tags); // {dart, flutter, ui}
print(tags.length); // 3
tags.removeWhere((t) => t.length < 3); // removes 'ui'
print(tags); // {dart, flutter}
tags.retainAll({'dart'}); // keep only elements found in the argument
print(tags); // {dart}
}The bulk methods have different effects:
| Method | Effect on the set |
|---|---|
| `addAll(iterable)` | Adds every element, skipping duplicates |
| `removeAll(iterable)` | Removes every element found in the argument |
| `retainAll(iterable)` | Keeps only elements found in the argument |
| `removeWhere(test)` | Removes elements for which `test` returns `true` |
| `retainWhere(test)` | Keeps elements for which `test` returns `true` |
| `clear()` | Empties the set |
How `add` decides
When you call add, the set computes the element's hashCode and looks in the matching bucket. If it finds an element that is == to the new one, it leaves the set unchanged and returns false. Otherwise it inserts the element and returns true.
For int, String, and other built-in value types, equality works the way you expect. For your own classes, the default == compares identity, so two objects with identical fields count as different elements unless you override == and hashCode.
Set operations
Sets support the operations from basic set theory. Each of union, intersection, and difference returns a new set and leaves both operands unchanged.
void main() {
final a = {1, 2, 3, 4};
final b = {3, 4, 5};
print(a.add(2)); // false, 2 is already present
print(a.union(b)); // {1, 2, 3, 4, 5}
print(a.intersection(b)); // {3, 4}
print(a.difference(b)); // {1, 2}
print(a.containsAll({1, 2})); // true, a superset check
print(a); // {1, 2, 3, 4}, unchanged by the operations above
print([1, 1, 2, 3, 3].toSet().length); // 3
}Dart has no built-in methods for subset or symmetric difference. You can build both from what exists:
void main() {
final a = {1, 2, 3, 4};
final b = {3, 4, 5};
final aInsideB = b.containsAll(a);
print(aInsideB); // false
final onlyInOne = a.union(b).difference(a.intersection(b));
print(onlyInOne); // {1, 2, 5}
}Both intersection and difference take an argument of type Set<Object?>, so you can pass a set of a different element type. They also use the argument's own idea of equality for the membership test. If the sets use different notions of equality (for example, one is a case-insensitive set), the result can surprise you.
Removing duplicates from a list
The most common use of a set is deduplication. Converting a list to a set and back keeps the first occurrence of each value, in the original order.
void main() {
final ids = [3, 1, 3, 2, 1];
final unique = ids.toSet().toList();
print(unique); // [3, 1, 2]
final seen = <int>{};
final dupes = ids.where((id) => !seen.add(id)).toList();
print(dupes); // [3, 1]
}The second half of the example uses the return value of add as a filter. seen.add(id) is false exactly when the id appeared before, so negating it selects repeated ids. The code works because toList() runs the lazy where once. If you stored the where result and iterated it twice, the second pass would start with a seen set that is already full and would select every element.
Iteration order
A set created by a literal, Set(), toSet(), or Set.from iterates in insertion order. That behavior comes from LinkedHashSet, the default implementation. It is guaranteed for that implementation, but a HashSet makes no ordering promise, and a SplayTreeSet iterates in sorted order. If your code depends on the order, create the specific type you need. A later chapter covers these variants.
Re-adding an existing element does not move it. The element keeps its original position.
Lookup, `first`, and the missing index
Because a set has no index, a few members behave differently from list members:
first,last, andsingleexist, because they come fromIterable. Bothfirstandlastthrow aStateErroron an empty set.elementAt(i)exists but walks the elements one by one, so it takes linear time. If you need it often, you probably want a list.lookup(x)returns the stored element that equalsx, ornullif none does. This is useful when equal objects carry extra information, or when you want to reuse an existing instance instead of a new duplicate.
void main() {
final names = {'Ada', 'Grace'};
print(names.lookup('Ada')); // Ada
print(names.lookup('Linus')); // null
print(names.first); // Ada
}lookup returns E?, so handle the null case as you would for a map lookup.
Constant and unmodifiable sets
A const set literal is immutable, and its elements must be compile-time constants. Adding a duplicate element to a const literal is a compile-time error, not a silent skip. Set.unmodifiable makes a read-only copy at runtime. In both cases, mutating methods throw UnsupportedError.
void main() {
const primes = {2, 3, 5};
try {
primes.add(7);
} on UnsupportedError {
print('const set cannot change');
}
final source = {1, 2};
final locked = Set<int>.unmodifiable(source);
source.add(3);
print(locked); // {1, 2}, the copy is independent
try {
locked.remove(1);
} on UnsupportedError {
print('unmodifiable set cannot change');
}
}Common errors
- Using
{}for an empty set. This creates a map unless the type context says otherwise. Write<T>{}. - Expecting two equal-looking objects to be one element. Without
==andhashCodeoverrides, they are two elements. - Mutating an element after adding it. If an element's
hashCodechanges while it is in the set, the set can no longer find it. Use immutable elements. - Assuming order from a
HashSetor after converting from another source. Choose the set type that guarantees what you need. - Calling
elementAtin a loop. Each call is linear, so the loop becomes quadratic.
Exercise
Given final a = ['x', 'y', 'x', 'z'] and final b = ['z', 'w', 'x'], write one expression that produces the elements that appear in both lists, with no duplicates. What does it evaluate to, and why does the result not depend on how many times 'x' appears in a?
Show answer
a.toSet().intersection(b.toSet()) evaluates to {x, z}. Converting each list to a set removes the repeated 'x' before the intersection runs, and a set can hold an element only once, so the count in the source list has no effect.
Exercise
What does this code print, and why? final s = <int>{}; print(s.add(1)); print(s.add(1)); print(s.length);
Show answer
It prints true, false, then 1. The first add inserts a new element. The second finds an equal element already present, leaves the set unchanged, and returns false.