Chapters

Hide chapters

Dart Apprentice: Fundamentals

First Edition · Flutter · Dart 2.18 · VS Code 1.71

Dart Apprentice: Fundamentals

Section 1: 16 chapters
Show chapters Hide chapters

13. Sets
Written by Jonathan Sande

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The word “set” has more than 400 different definitions in the English language. Are you set to set the set set of sets on the set? That is to say: Are you ready to put the fixed group of mathematical collections on the TV?

The term’s meaning in Dart relates closely to the mathematical meaning. A set is a collection of elements where the order isn’t important and duplicate elements are ignored.

This contrasts with Dart lists, in which order is important and duplicates are allowed.

Because of their characteristics, sets can be faster than lists for certain operations, especially when dealing with large datasets. This makes them ideal for quickly checking whether an element exists in a collection. If you wanted to know whether a list of desserts contained donuts, you’d have to check each dessert to find out. Not so with sets. You ask a set if there are donuts, and the set tells you immediately: Yes, there’s one donut!

Creating a Set

You can create an empty set in Dart using the Set type annotation like so:

final Set<int> someSet = {};

The generic syntax with int in angle brackets tells Dart the set allows only integers. You could just as easily make the type String or bool or double, though.

The following form is shorter but identical in result:

final someSet = <int>{};

The curly braces are the same symbols used for sets in mathematics, which should help you remember them. Be sure to distinguish curly braces in this context from their use for defining scopes, though.

You can also use type inference with a set literal to let Dart determine the element types in the set.

final anotherSet = {1, 2, 3, 1};
print(anotherSet);

Because the set literal contains only integers, Dart can infer the type as Set<int>.

Additionally, you probably noticed there are two 1s there, but because sets ignore duplicates, anotherSet ends up with only one 1. Run that code to verify that anotherSet has only one 1:

{1, 2, 3}

Operations on a Set

In this section, you’ll see some general collection operations that apply to sets.

Checking the Contents

To see whether a set contains an item, use the contains method, which returns a bool.

final desserts = {'cake', 'pie', 'donut'};
print(desserts.contains('cake'));    // true
print(desserts.contains('cookies')); // false

Adding Single Elements

Like growable lists, you can add and remove elements in a set. To add an element, use the add method:

final drinks = <String>{};
drinks.add('cola');
drinks.add('water');
drinks.add('cola');
print(drinks);
{cola, water}

Removing Elements

You can also remove elements using the remove method.

drinks.remove('water');
{cola}

Adding Multiple Elements

Use addAll to add elements from a list into a set:

drinks.addAll(['juice', 'coffee', 'milk']);
{cola, juice, coffee, milk}

Looping Over the Elements

Like lists, sets are also iterable collections, so you can iterate over the elements with a for-in loop.

for (final drink in drinks) {
  print("I'm drinking $drink.");
}
I'm drinking cola.
I'm drinking juice.
I'm drinking coffee.
I'm drinking milk.

Copying Sets

A set’s elements are mutable in the same way a list’s elements are. If you forget that, you might be surprised if you try to copy a set in the following way:

final beverages = drinks;
print(drinks);

beverages.remove('milk');
print(drinks);
print(beverages);
{cola, juice, coffee, milk}
{cola, juice, coffee}
{cola, juice, coffee}
final liquids = drinks.toSet();
print(drinks);

liquids.remove('coffee');
print(drinks);
print(liquids);
{cola, juice, coffee}
{cola, juice, coffee}
{cola, juice}

Other Operations

Almost everything you learned about lists in Chapter 12, “Lists”, also applies to sets. Specifically, you can perform any of the following operations with sets:

Exercise

  1. Create an empty set of type String and name it animals.
  2. Add three animals to it.
  3. Check if the set contains 'sheep'.
  4. Remove one of the animals.

Set Relationships

Sometimes you have multiple datasets and want to know how they compare. Set A and Set B in the diagram below both contain integers, some of which are the same and others are different:

Xup E Wed Q 0 9 4 9 6 7 2 8 6

Pil U Qas F 5 6 7 6 9 1 1

Intersections

Finding the intersection of two sets in Dart tells you the common elements in them. The numbers 1 and 4 are the intersection of Set A and Set B:

Lep A Vif H 4 1 8 2 8 7 2
Aphovzetvauw

final setA = {8, 2, 3, 1, 4};
final setB = {1, 6, 5, 4};
final intersection = setA.intersection(setB);
{1, 4}

Unions

Combining two sets gives you the union. If there are any duplicates between the subsets, the union only includes them once:

Zax U Zul Q 4 7 1 1 1 2 5
Eciak

final union = setA.union(setB);
{8, 2, 3, 1, 4, 6, 5}

Difference

The difference is what one set contains that another does not. You can think of it as subtracting one set from another. In the image below, Set A is different than Set B because Set A includes the values 8, 2 and 3 whereas Set B doesn’t. Or an alternate way of stating that would be: Set A minus Set B equals the new set {8, 2, 3}:

Muw U Giz C 6 7 6 5 6 1 4
Feqjafimno iw O - P

final differenceA = setA.difference(setB);
{8, 2, 3}
Vam U Leq R 3 3 8 7 7 7 2
Cuynuhezra ov C - E

final differenceB = setB.difference(setA);
{6, 5}

Exercise

Find the intersection and union of the following three sets:

final nullSafe = {'Swift', 'Dart', 'Kotlin'};
final pointy = {'Sword', 'Pencil', 'Dart'};
final dWords = {'Dart', 'Dragon', 'Double'};

Finding Duplicates

Because adding to and checking a set’s elements are fast operations, one application of this data structure is for finding duplicate elements in other collections.

Random Number Generation

Many applications require randomization, especially games. This makes your program more interesting and less predictable. Here are a few examples of where you would want to generate random values:

Generating a List of Random Integers

You can generate random values in Dart with the Random class from the dart:math library.

import 'dart:math';
// 1
final randomGenerator = Random();
final randomIntList = <int>[];

for (int i = 0; i < 10; i++) {
  // 2
  final randomInt = randomGenerator.nextInt(10) + 1;
  randomIntList.add(randomInt);
}

print(randomIntList);
[8, 3, 2, 3, 7, 7, 4, 5, 6, 2]

Finding Duplicate Integers in the List

Now, add the following code below what you wrote before:

// 1
final uniqueValues = <int>{};
final duplicates = <int>{};

for (int number in randomIntList) {
  // 2
  if (uniqueValues.contains(number)) {
    duplicates.add(number);
  }
  // 3
  uniqueValues.add(number);
}

print(duplicates);
[2, 4, 3, 7, 9, 5, 1, 10, 2, 9]
{2, 9}

Challenges

The following challenges will test your knowledge of sets. It’s best if you try to solve them yourself, but solutions are available with the supplementary materials for this book if you get stuck.

Challenge 1: A Unique Request

Write a function that takes a paragraph of text and returns a collection of unique String characters that the text contains.

Challenge 2: Symmetric Difference

Earlier in the chapter, you found the intersection and the union of the following sets:

final setA = {8, 2, 3, 1, 4};
final setB = {1, 6, 5, 4};
Fiv A Zel W 0 0 3 1 4 7 8
Myfbubzas Radwolukpu

Key Points

  • Sets store unordered collections of unique elements.
  • Adding, removing and checking for a value’s existence in a set are all fast operations.
  • The intersection of two sets is the shared values between them.
  • A union of two sets is found by combining the values of both sets.
  • The difference of two sets is found by subtracting one set from the other.
  • One application of sets is for finding duplicate elements in other collections.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now