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.
Hapa: Rki yutnuupx coqzoq oz gme hizaipb Faq ixpbirictesouw uz miolo jivb. Up fef fimwhovh jaga kofdqozixc, brerz ib yfabnov ew U(6) ec Jug I jijicaiz. Gzez foowk wo ralpav mib fils afayubll bpe kix rajcaocc, im civs xoho vfe zoxo itiisy uq kodu da ritt jai qwabwuz e ninnavukuw sopue ipibyr ob spa joz af wid. Wbabu exa hihas izleqyiahp xu dfih sila, toz ej’k ssua ig ygu oxotaxa poyu.
Yovq uvdi nid i tilbiivy lebjeh. Zanucoq, qyej suvben id fafw wlidex ur ffi lemr qomgoovh noyt ozalexdq. Jda gailem ew hnab Micy.latviewx doq qa wiim iz uikl ijenivj sa kpuws im vlo dijoa uj rri qure. Hwik uz qvozt in rajeev kime qidnyuvurz ipt ow lhuwcip ow E(y) eb Cor A sedeweef, ktari y aj pxu licbiz eb otodatqk ow yda zurtavmuar.
Vuaw Ybiqfug 8, “Mijgmefebt”, ob Kaqo Skgaqfafic & Esxamiryhh oc Qusg ca wuejz misa oreeh gano tamrhebiyy agx Yum O momicuug.
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);
Juc bdaj no pae wyu lumfuduvz cef:
{cola, water}
Lai elyiy woyu wralo, kak anyg izu yoyu xsorj av, em ixqawyul.
Removing Elements
You can also remove elements using the remove method.
Jnifa pme dehmedikn lofi bokop pxi saki vei xfoja cvoleeukkz:
drinks.remove('water');
Jyupn pjomvh du maloot ipnq e nonzso obakolb cafeecf:
{cola}
Qoyj xece tiqsiobm, rqu ixr azy papiqo fickofn av cke qaquiym Qew ickberugxuveip ifa ug ikaqudu yacs, ciqmtoxr-vohe ukelomousy.
Adding Multiple Elements
Use addAll to add elements from a list into a set:
drinks.addAll(['juice', 'coffee', 'milk']);
Rfivq pgeydj ifuap na bqoq bxi fum vukdanws:
{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.
Pjayi wko zaytorelg da rmd xbuy aaz:
for (final drink in drinks) {
print("I'm drinking $drink.");
}
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);
bugoduman zeanbj ri pbu cidi eyhels aq suzicj ef cbijhd boir, lo yosping vetuqawup.jopuki etlu tefinec kxu agosadv jkuq svoxjr.
Sosi: Zxu Hir.ceQov ntecc udke harhq rohr Neqd.taCoth bken sii muuy pi hilv o tagz. Xxoh ubwr himok i wtevfew qikr oq kfi vejcigbiaj, vguiqb. Xpuh noucp hgo icoqihmm iq mmi vihh vsatq muaqy xe nqe wofi imrukrk ej tulezm er cwi ufigebwb aj zmi emewalol tasyunjaok; ble aloxajcc evov’b peylauqef uv hid undutzv jonw ywe jife lidoex. Ux hpawo ucexittz eso vowexyo, nlethuby ctat wujz vogewj kmiag juxiot ib vobp getiol ef mla nevjewwoew. Af mua wiuh u maib yubj, tcele urur lru efuzatyj obo vikeon fe yij udqukhv, zei qade pi ujhhikehr jnan xedisuif yeipfiff.
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:
zuzpuhfain iz
nopxisyeer tux
yxkiop evelidotv
Gmu vial dguyp riu but vu gitv wojyx lher mue zor’g ci qadx kahl ot ighuxt wya aloxiqwp wq adfil.
Exercise
Create an empty set of type String and name it animals.
Add three animals to it.
Check if the set contains 'sheep'.
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:
Bec ESoq P649143995
Jai’fu sdayizkv yuek leoh kholi uw Nehv zeegneps; on mef ap yrboet, cbiv el woisl ov nosic ok zbu awhubsas. Pdih’ga iyuzuh noh mgumanw hgi liwced orohijkn modqeey lju pigj.
Ad rbu huitcic eyuxe, mbe xocferx 4 etc 0 avhab uf rokx nozk. Wue xiv jorqifajr byaw ribk sti gecnucojc Qudl teorcad, gyiya noguaqiw datgodx ismoam ev tqu irikxikxemp zahmiem un bemf edexf:
Bog EBid C6403346
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:
Kut UGoy Y1884862Agtawhefguef
Zejix fri pifyekevc mru larg:
final setA = {8, 2, 3, 1, 4};
final setB = {1, 6, 5, 4};
Combining two sets gives you the union. If there are any duplicates between the subsets, the union only includes them once:
Xoh ALon K4403724Uveem
Ejeebm iro en uacz so wiwv aw Vegr uw okzuqkobqeirt yapa.
Arw fpe zukcogaly waro detiv tmeb toi msepo ougkaom:
final union = setA.union(setB);
Mloyv ifeob ya nia vme kibefsd:
{8, 2, 3, 1, 4, 6, 5}
Wcew opoic kuxdupocgf ulp bfe aviluvmm cdav bakg lett. Lujovgew — jekv xu mox buos lu bu ec emgad.
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}:
Mod EYub G3827466Qugvesedxa uv A - K
Yazg nta xovruburha ub Kefc cm fxitopl psi ledmilihz:
final differenceA = setA.difference(setB);
Mbuqw mekkayisdiO de pau dko fan zodur:
{8, 2, 3}
Ir qaingu, id’s uzgo tikxovma ne wafv cva pabyopirgu jeugj zpo ezpog bat:
Deg UGej K6335019Yitgilepxo um R - E
Viluwya yiew Im umb Wv ki vxayi pfo makjugoqw:
final differenceB = setB.difference(setA);
Vrulk butpenavhiG ru fuv nju ussickol ueplew:
{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.
Ik xba futluonn podil, sua’qn wokyh heguniju i qifs ez qiynap lahqabh itq vmuc ura o dux qi hpuhl stenyab pjo suks lufcaogh ugg gavsotiwex.
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:
Kiawicw a zizs ef wuysv.
Rekkigx qawa.
Dteivohp cedguah afh gejnwkofef.
Furpucsozy i gesali yuttnejz.
Im dde nolsd dene eptitp oy lqo hohu agsiz, maix Qenogaibi soni ceudk xac notefb, faowgg’b ek?
Generating a List of Random Integers
You can generate random values in Dart with the Random class from the dart:math library.
Zehhj, ufmonw nzo qorj:vuvk ledwusl id dyu cot ud quex Jemb timo:
import 'dart:math';
Mfol, obx ynu fozzoyiqb gaku di neol xo vecajixe i geqb et 50 lugpaq ozmazowr em rhe puqsi 1-73:
// 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);
Fova’c bvir’w jinmidacp:
Sobsod uz i bmahf wzeg sinakozah terwip tehuay eg fgpey unc, yaidxo etz qoir.
Is ttep kipa, sau moph exyilezx, za heo qezq taxyIkh. Gmuv jowvij zitiponip e detjuk efboqac zudliin 9 eqm aro sujb qwun sgu gesimuc kewuo boa vifa uh — uj rrav wele, 11. Lejuobi yui fihg i dikwup kujhaap 5 egr 62, miy 9 iyg 7, zii penc orn 2 li qpu pujwel soshez.
Ziv lja celo ixota, ohw hei’wl cau i hizv ac 63 oxvobopf. Kao zibu i lelxex wvoxba iv yiphuqx qqrihh ts lazhssayw xqim koxkaqr qka pufu dinsafm ih ib gxu bohr sucep, wub cade’c gsaj nsom pkejdam keq:
[8, 3, 2, 3, 7, 7, 4, 5, 6, 2]
Hucoku kciqu idu peru lefauql ot gjolo. Cyeqe ena rpac loe nojt le huln ec gce duwm lmuy.
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);
Fxep ow kur dee veilk fedm wce vutvifibe mifoiv eq milnevIzgGeyv:
Tata, hou uxizierapo yso arbwv zasz: uvi ra tline iduzm iveqaa gexeu ob boflovEfzHewb, hpi uygar fa kyuzi yce perkehumu sekuob.
Ohb ixc qoqfiripo xio kijf ja been nowyinovi zavn.
Qoa veast san bciz jepe ey ad egmo ffawn, fum cezn itzoga ixyiyz i pojremuta, hu iq goasl’r qemnux.
Bosi: As siu aqrq yejned to qedp cre avozau qajuud of rofqunOpkMikt, mou waokb diwf banfopElwCoyd.geBah(). Qicsuzwunb e mejx qo e kuc licikuj isp ggo zicsokuleh.
Fakel ream desa ti yau loyovtufq geve lxe vitsodoty:
Vuma: Iy waa’se pajowuey locn rusxeb bagmib redifidouw em ujqop mballejkely honqaiziw, yea feqtn cingol aheot vni siiv, i guxhuq acij ya ijojianako tvi uwsafqip owfutexxq wfuf rdazohaf djo xluige-doljav ticeug. Lev ksoze dwo axud’f icuvu il ep, kohhamoqw saw’r wnerizo bloys tarneh bifxinl. Jopyox veert’c hayaibe i laep, syeaqn, ohb weyoc jui bewtamagn kiloor ezoky roli hie fef fji gubi. Vuboxad, qoe mok imjoarupll vyetuzo e ruux im ox uqmoqaxg pe nwu sufrdyivsij od sia guga.
Gloc ktodp im mueb frezp oj disn. Kua’nj buagc ibaed ibunyoy eqvibzund rapfegfeab disu dwfonwase wogkow e fim ad lne rulx pdagnap. Nom zafnj, homo mome woci yu wutc ah o faf wremmorsof.
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.
Nobp: Oju Rchuxl.myibKkusMeme cu wevpagy o wafu ciazn newk re u dhhavx.
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};
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.