CodeBlanks Logo Icon CodeBlanks

Set

Learn unique collections with Set<T>.

Set<T>

Set<T> is a collection that holds unique elements. If you add the same value twice the second is ignored. This is useful when you want to avoid duplicates.

Create a Set with var tags = <String>{'dart', 'flutter'};. The curly braces {} mark it as a Set. The add method appends an element; if the value already exists nothing changes.

A Set is not ordered; insertion order may be preserved but index access is not supported. The length gives the count of unique elements.

Set operations

To add an element use set.add(value). The element count comes from set.length. Printing a Set with print(set) shows it as {a, b, c}.

Example: var s = <int>{1, 2, 2, 3}; print(s);. Output: {1, 2, 3}. The duplicate 2 is kept once.

The advantage of a Set is automatic duplicate removal. For example it prevents the same tag from being saved twice in a user tag list.

Practice Create a tag set

Create a tag set with <String>{'dart', 'flutter', 'dart'}. Print the set contents with print. Then add 'web' with add and print the length.

Starter code

main.dart
void main() {
  // create a String set, add a duplicate element
  // print the set contents and its length
}

Sample solution

main.dart
void main() {
  var tags = <String>{'dart', 'flutter', 'dart'};
  print(tags);
  tags.add('web');
  print(tags.length);
}

Expected output

{dart, flutter}
3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if you add the same element to a Set twice?

main.dart
var s = <int>{1, 2};
s.add(1);
  • It throws an error
  • The second is ignored, the Set stays the same Correct answer
  • Two 1s appear
  • The Set gets sorted

Explanation: a Set is unique so a duplicate add is ignored.

2 Creating a Set

Question
var tags = <String>____{'dart', 'flutter'};
Answer
var tags = <String>{}{'dart', 'flutter'};

Explanation: a Set is created with curly braces.

3 Match the Set parts

Term Meaning
<String>{...} Set creation
add(x) Add element
{1, 2, 3} Output format
length Unique count

All lessons in Intermediate